Connect a JWT to the User property in the Controller

☆樱花仙子☆ 提交于 2019-12-13 03:37:56

问题


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

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

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

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.

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.

Here are variations that I have tried:

  • 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());
    });

       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.

What do I need to do to get the User property (that is part of the Controller base class) to be populated with my claims?


回答1:


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

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();
    });
}


来源:https://stackoverflow.com/questions/58599759/connect-a-jwt-to-the-user-property-in-the-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!