Asp.net core 无法识别.NET Core 2 Web API JWT令牌

Asp.net core 无法识别.NET Core 2 Web API JWT令牌,asp.net-core,asp.net-web-api2,jwt,Asp.net Core,Asp.net Web Api2,Jwt,我随后在我的Web API应用程序中配置了JWT授权。令牌生成和分发工作正常,但当我将带有令牌的请求发送回服务器时,它不会填充标识,因此如果需要授权,它将失败 我已经用一个前端和邮递员测试过了。两者最终都不返回任何内容(如果Authorize decorator-User.Identity.isAuthorized为false),或者使用decorator返回404。我已确认令牌已正确发送 我也在使用身份,如果这很重要的话 配置服务方法 public void ConfigureServ

我随后在我的Web API应用程序中配置了JWT授权。令牌生成和分发工作正常,但当我将带有令牌的请求发送回服务器时,它不会填充标识,因此如果需要授权,它将失败

我已经用一个前端和邮递员测试过了。两者最终都不返回任何内容(如果Authorize decorator-User.Identity.isAuthorized为false),或者使用decorator返回404。我已确认令牌已正确发送

我也在使用身份,如果这很重要的话

配置服务方法

    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/"
 }
“Jwt”:{
“密钥”:“密钥”,
“发行人”:http://localhost:53530/",
“观众”: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);
    }
[HttpGet(“当前用户”),授权]
公共异步任务GetCurrentUser()
{
var username=User.Identity.Name;
返回wait\u context.ApplicationUsers.SingleOrDefaultAsync(u=>u.UserName==UserName);
}

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

services.AddAuthorization(auth =>
{
    auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
        .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
        .RequireAuthenticatedUser().Build());
});
然后我在控制器上装饰了

[Authorize("Bearer"]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
几天来,我一直在处理这个问题,尝试不同的教程,所以我知道在没有政策的情况下,这在某一点上是有效的。不知道为什么我这次需要它,或者为什么它不是教程的一部分


如果有人一开始就知道我搞砸了什么,我会洗耳恭听。

我知道了。我必须添加一个新的授权策略

services.AddAuthorization(auth =>
{
    auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
        .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
        .RequireAuthenticatedUser().Build());
});
然后我在控制器上装饰了

[Authorize("Bearer"]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
几天来,我一直在处理这个问题,尝试不同的教程,所以我知道在没有政策的情况下,这在某一点上是有效的。不知道为什么我这次需要它,或者为什么它不是教程的一部分

如果有人一开始就知道我搞砸了什么,我会洗耳恭听。

我遇到了同样的问题(.net core 2.1),并且非常高兴使用您的答案@atfergs来实现它

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

只需将控制器装饰成

[Authorize("Bearer"]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
考虑以下设置

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

是真的:)

干杯

我遇到了同样的问题(.net core 2.1),并且非常高兴使用您的答案@atfergs使其生效

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

只需将控制器装饰成

[Authorize("Bearer"]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
考虑以下设置

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

是真的:)

干杯

希望我的答案有帮助希望我的答案有帮助