简体   繁体   English

JWT .NET 5 MVC 应用程序中的授权

[英]JWT Authorization in .NET 5 MVC Application

I want to know how I can handle auhtorization using jwt for my mvc controllers in .net 5 webapp.我想知道如何在 .net 5 webapp 中为我的 mvc 控制器使用 jwt 来处理授权。 The token generating functions are already written and its works perfectly in postman (by passing bearer token), but trivial redirect from controller to other one with [Authorize] attribute dosent work - 401 response.令牌生成函数已经编写完毕,它在 postman 中完美运行(通过传递不记名令牌),但从 controller 重定向到具有 [Authorize] 属性的其他函数的微不足道的工作 - 401 响应。 I checked details of request and authorization header seems to be missing.我检查了请求和授权的详细信息 header 似乎丢失了。 Should i create my own middleware to refill authorization header in every request / redirect to other mvc controller or jwt framework for .net do it for me by passing few rules in eg Startup class? Should i create my own middleware to refill authorization header in every request / redirect to other mvc controller or jwt framework for .net do it for me by passing few rules in eg Startup class? how it should work?它应该如何工作?

HomeController (main page) HomeController(主页)

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

PersonController个人控制器

 [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?}");
            });
        }
    }

You use AddJwtBearer to secure APIs and typically you provide the JWT access token using the authorization header in the incoming request and AddJwtBearer will convert the token to a User instance.您使用AddJwtBearer来保护API ,通常您使用传入请求中的授权 header 提供 JWT访问令牌,并且 AddJwtBearer 会将令牌转换为用户实例。

This code makes no sense:这段代码没有意义:

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

Because you can't include the necessary token in the authorization response header through an redirect.因为您无法通过重定向在授权响应 header 中包含必要的令牌。 The Redirect is for humans visiting your web site and not for API access.重定向适用于访问您的 web 站点的人,而不适用于 API 访问。

So I think you are mixing up what the browser/users can do, and what API-access means.所以我认为你混淆了浏览器/用户可以做什么,以及 API 访问意味着什么。

I would first create one ASP.NET core service for humans to visit and then a separate service instance for the API, that the first service can send requests to.我将首先创建一个 ASP.NET 核心服务供人类访问,然后为 API 创建一个单独的服务实例,第一个服务可以向其发送请求。

Also, AddJwtBearer will typically not accept any tokens genererated by yourself, instead you should have an authorization service (like IdentityServer ), issuing the tokens for you.此外, AddJwtBearer 通常不会接受您自己生成的任何令牌,而是您应该有一个授权服务(如IdentityServer ),为您颁发令牌。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM