【问题标题】:JWT Authorization in .NET 5 MVC Application.NET 5 MVC 应用程序中的 JWT 授权
【发布时间】:2022-01-14 02:04:00
【问题描述】:

我想知道如何在 .net 5 Web 应用程序中使用 jwt 为我的 MVC 控制器处理授权。 令牌生成函数已经编写好了,它在邮递员中完美运行(绕过承载令牌),但是从控制器到另一个具有 [Authorize] 属性的微不足道的重定向不起作用 - 401 响应。我检查了请求的详细信息,授权标头似乎丢失了。 我是否应该创建自己的中间件以在每个请求/重定向到其他 MVC 控制器或 .net 的 jwt 框架中重新填充授权标头,通过在例如启动类中传递一些规则来为我做这件事?它应该如何工作?

HomeController(主页)

    [HttpGet]
        public IActionResult Redirect()
        {
            var token = new JWTService().GenerateToken("test").Token;
            return Redirect("~/Person");
        }

人员控制器

 [Authorize(AuthenticationSchemes  = JwtBearerDefaults.AuthenticationScheme)]
        public IActionResult Index()
        {
            return View();
        }
 public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidAudience = "aaaa",
                    ValidIssuer = "aaaa",
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"))
                };
            });

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseStaticFiles();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseCookiePolicy();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }

【问题讨论】:

    标签: c# .net model-view-controller jwt token


    【解决方案1】:

    您使用 AddJwtBearer 来保护 API,通常您使用传入请求中的授权标头提供 JWT 访问令牌,并且 AddJwtBearer 会将令牌转换为 User 实例。

    这段代码没有意义:

        [HttpGet]
        public IActionResult Redirect()
        {
            var token = new JWTService().GenerateToken("test").Token;
            return Redirect("~/Person");
        }
    

    因为您无法通过重定向在授权响应标头中包含必要的令牌。重定向适用于访问您的网站的人,而不是 API 访问。

    所以我认为您混淆了浏览器/用户可以做什么,以及 API 访问意味着什么。

    我将首先创建一个供人类访问的 ASP.NET 核心服务,然后为 API 创建一个单独的服务实例,第一个服务可以向其发送请求。

    此外,AddJwtBearer 通常不会接受您自己生成的任何令牌,而是您应该有一个授权服务(如 IdentityServer),为您颁发令牌。

    【讨论】:

      猜你喜欢
      • 2021-12-04
      • 2019-08-02
      • 2019-03-20
      • 2018-09-22
      • 2015-08-02
      • 1970-01-01
      • 2022-01-16
      • 2021-11-06
      • 2019-05-01
      相关资源
      最近更新 更多