本文介绍了将JWT连接到Controller中的User属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web API .NET Core 3.0服务.它获得一个包含带有声明的JWT的标头.

I have a Web API .NET Core 3.0 Service. It gets a header that contains a JWT with claims.

我在Startup.cs的ConfigureServices中添加了以下内容,以将JWT映射到.NET Core身份验证系统:

I added the following to ConfigureServices in Startup.cs to map my JWT to the .NET Core Authentication system:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(configureOptions =>
{
    configureOptions.Events = new JwtBearerEvents()
    {
        OnMessageReceived = context =>
        {
            context.Token = context.HttpContext.Request.Headers["X-JWT-Assertion"];
            return Task.CompletedTask;
        }
    };
});

我还在Startup.cs的Configure中添加了app.UseAuthentication();.

I also added app.UseAuthentication(); to Configure in Startup.cs.

然后我启动服务并对其调用HTTP GET操作.当我这样做时,可以看到context.Token设置为我的JWT.如果我将JWT移交给 https://JWT.io ,则表明它有很多主张.

I then fire up my service and call an HTTP GET operation on it. When I do, I can see that the context.Token is set to my JWT. If I take that JWT over to https://JWT.io it shows that it has many claims.

但是GET操作中的断点显示User.Claims为空.将JWT连接到用户所需的一切都没有发生.

But a break point in the GET operation shows that User.Claims is empty. What ever is needed to connect the JWT to the User is not happening.

这是我尝试过的变体:

  • 在我的控制器上方添加[Authorize]:
    结果: 401错误:未经授权
  • 在控制器上方添加[Authorize(JwtBearerDefaults.AuthenticationScheme)]
    结果:找不到名为"Bearer"的AuthorizationPolicy.
  • 在ConfigureServices中添加services.AddAuthorization(),并在我的控制器上方添加[Authorize]
    结果: 401错误:未经授权
  • [Authorize(JwtBearerDefaults.AuthenticationScheme)]添加到我的控制器上方,并将下面的代码添加到ConfigureServices中:
  • Add [Authorize] above my controller:
    Result: 401 Error: Unauthorized
  • Add [Authorize(JwtBearerDefaults.AuthenticationScheme)] above my controller
    Result: The AuthorizationPolicy named: 'Bearer' was not found.
  • Add services.AddAuthorization() in ConfigureServices and [Authorize] above my controller
    Result: 401 Error: Unauthorized
  • Add [Authorize(JwtBearerDefaults.AuthenticationScheme)] above my controller and code below to ConfigureServices :
    services.AddAuthorization(auth =>
    {
        auth.AddPolicy(JwtBearerDefaults.AuthenticationScheme, 
            new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build());
    });

      结果: 401错误:未授权

       Result: 401 Error: Unauthorized

要清楚,我不想做任何授权,但我读到,可能需要添加权限才能将声明映射到用户.

To be clear, I don't want to do any Authorization, but I read that adding it may be needed to map the claims to the user.

我需要做什么才能使User属性(属于Controller基类的一部分)填充我的声明?

推荐答案

我怀疑您的配置有问题.在ConfigureServices方法中,应如下所示:

I suspect there is something wrong in your configuration. In the ConfigureServices method it should be as follows:

services.AddAuthentication(options =>
{
   options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
   options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters()
    {
       ValidateIssuer = true,
       ValidateAudience = true,
       ValidateLifetime = true,
       ValidateIssuerSigningKey = true,
       ValidIssuer = Configuration["Jwt:Issuer"],
       ValidAudience = Configuration["Jwt:Issuer"],
       IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
    };
});

然后在Configure方法中,应如下所示:

Then in the Configure method it should be as follows:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    ...................

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization(); // These two must be before `UseEndpoints` and after `UseRouting`

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
    });
}

这篇关于将JWT连接到Controller中的User属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 20:18