繁体   English   中英

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

[英]JWT Authorization in .NET 5 MVC Application

我想知道如何在 .net 5 webapp 中为我的 mvc 控制器使用 jwt 来处理授权。 令牌生成函数已经编写完毕,它在 postman 中完美运行(通过传递不记名令牌),但从 controller 重定向到具有 [Authorize] 属性的其他函数的微不足道的工作 - 401 响应。 我检查了请求和授权的详细信息 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? 它应该如何工作?

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

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

这段代码没有意义:

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

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

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

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

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

暂无
暂无

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

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