【问题标题】:.NET Core 2 Web API JWT token not recognized.NET Core 2 Web API JWT 令牌无法识别
【发布时间】:2018-07-18 09:37:48
【问题描述】:

我关注this tutorial 在我的 Web API 应用程序中配置 JWT 授权。令牌生成和分发工作正常,但是当我使用令牌向服务器发送请求时,它不会填充身份,因此如果需要授权,它会失败。

我已经使用 reactjs 前端和 Postman 进行了测试。两者最终都没有返回任何内容(没有授权装饰器 - User.Identity.isAuthorized 为假),或者装饰器返回 404。我已确认令牌已正确发送。

我也在使用 Identity,如果这很重要的话。

ConfigureServices 方法

    public void ConfigureServices(IServiceCollection services)
    {
        ...

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

配置方法

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseAuthentication();

        app.UseCors("SiteCorsPolicy");

        app.UseMvc();

        ...
    }

构建令牌的功能

    private string BuildToken(AuthViewModel user)
    {
        var claims = new[]
        {
            new Claim(JwtRegisteredClaimNames.Sub, user.Username),
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
        };

        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        var token = new JwtSecurityToken
        (
            _config["Jwt:Issuer"],
            _config["Jwt:Audience"],
            //claims,
            expires: DateTime.Now.AddMinutes(30),
            signingCredentials: creds
        );

        return new JwtSecurityTokenHandler().WriteToken(token);
    }

摘自 appsettings.json

"Jwt": {
    "Key": "<secret stuff>",
    "Issuer": "http://localhost:53530/",
    "Audience": "http://localhost:8080/"
 }

我正在尝试调用但失败的测试函数

    [HttpGet("currentuser"), Authorize]
    public async Task<ApplicationUser> GetCurrentUser()
    {
        var username = User.Identity.Name;

        return await _context.ApplicationUsers.SingleOrDefaultAsync(u => u.UserName == username);
    }

【问题讨论】:

标签: asp.net-core asp.net-web-api2 jwt


【解决方案1】:

我想通了。我必须添加一个新的授权策略。

services.AddAuthorization(auth =>
{
    auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
        .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
        .RequireAuthenticatedUser().Build());
});

然后我用

装饰了控制器
[Authorize("Bearer"]

我已经搞砸了几天,尝试了不同的教程,所以我知道这在没有政策的情况下是有效的。不知道为什么我这次需要它,或者为什么它不是教程的一部分。

如果有人知道我一开始搞砸了什么,我会全神贯注。

【讨论】:

    【解决方案2】:

    我遇到了同样的问题(.net core 2.1),并且很高兴使用您的回答 @atfergs 使其正常工作。

    在摆弄了整个设置之后,我发现不需要新的授权策略。

    用控制器来装饰就足够了

    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
    

    考虑以下设置

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {...}
    

    现在

        User?.Identity?.IsAuthenticated
    

    是真的:)

    干杯!

    【讨论】:

      猜你喜欢
      • 2021-06-27
      • 2019-03-10
      • 2020-06-28
      • 2020-05-05
      • 2017-08-20
      • 2019-01-21
      • 2020-11-16
      • 1970-01-01
      • 2015-01-02
      相关资源
      最近更新 更多