AspNetCore 2.1承载令牌认证 - 当前用户为空

时间:2018-06-03 19:43:39

标签: c# asp.net-core asp.net-identity jwt entity-framework-core

我有一个应用程序在用户登录时请求令牌。 然后使用以下标头传递该标记:

Authorization: Bearer <TOKEN>

我在startup.cs(aspnet core 2.1)上有以下代码:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvcCore()
            .SetCompatibilityVersion(CompatibilityVersion.Latest)
            .AddFormatterMappings()
            .AddJsonFormatters()
            .AddCors()
            .AddAuthorization(o =>
            {
                o.DefaultPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme)
                 .RequireAuthenticatedUser()
                 .Build();
            });

    /* Code... */

    ConfigureAuthentication(services);

    /* Code... */
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseAuthentication()
       .UseMiddleware<ExceptionMiddleware>(container)
       .UseCors(x =>
       {
           x.WithOrigins("*")
           .AllowAnyMethod()
           .AllowCredentials()
           .AllowAnyHeader()
           .Build();
       });

    /* Code... */
}

private void ConfigureAuthentication(IServiceCollection services)
{
    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
        var tokenProvider = new HumbleTokenProvider(container);
        options.TokenValidationParameters = tokenProvider.GetValidationParameters();
        options.RequireHttpsMetadata = false;
    });
}

要在用户登录时创建令牌,我TokenProvider服务:

public class RsaJwtTokenProvider : ITokenProvider
{
    readonly IConfiguration configuration;
    readonly IDateFactory dateFactory;

    readonly RsaSecurityKey _key;
    readonly string _algorithm;
    readonly string _issuer;
    readonly string _audience;

    public RsaJwtTokenProvider(
            IConfiguration configuration,
            IDateFactory dateFactory
        )
    {
        this.configuration = configuration;
        this.dateFactory = dateFactory;

        var parameters = new CspParameters { KeyContainerName = configuration.GetSection("TokenAuthentication:SecretKey").Value };
        var provider = new RSACryptoServiceProvider(2048, parameters);

        _key = new RsaSecurityKey(provider);

        _algorithm = SecurityAlgorithms.RsaSha256Signature;
        _issuer = configuration.GetSection("TokenAuthentication:Issuer").Value;
        _audience = configuration.GetSection("TokenAuthentication:Audience").Value;
    }

    public (string Token, int Expires) CreateToken(string userName, string UserId)
    {
        JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();

        var claims = new List<Claim>()
        {
            new Claim(ClaimTypes.NameIdentifier, UserId),
            new Claim(ClaimTypes.Name, userName)
        };

        ClaimsIdentity identity = new ClaimsIdentity(claims, "jwt");

        int expiresIn = int.Parse(configuration.GetSection("TokenAuthentication:Validaty").Value);
        DateTime expires = dateFactory.Now.AddMinutes(expiresIn).ToUniversalTime();
        SecurityToken token = tokenHandler.CreateJwtSecurityToken(new SecurityTokenDescriptor
        {
            Audience = _audience,
            Issuer = _issuer,
            SigningCredentials = new SigningCredentials(_key, _algorithm),
            Expires = expires,
            Subject = identity
        });

        return (tokenHandler.WriteToken(token), expiresIn);
    }

    public TokenValidationParameters GetValidationParameters()
    {

        return new TokenValidationParameters
        {
            // The signing key must match!
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = _key,

            // Validate the JWT Issuer (iss) claim
            ValidateIssuer = true,
            ValidIssuer = _issuer,
            // Validate the JWT Audience (aud) claim
            ValidateAudience = true,
            ValidAudience = _audience,

            // Validate the token expiry
            ValidateLifetime = true,
            // If you want to allow a certain amount of clock drift, set that here:
            ClockSkew = TimeSpan.Zero
        };
    }
}

如您所见,TokenValidationParameters中使用的AddJwtBearerGetValidationParameters上面的代码提供。

我对此的第一个看法是,startup授权/身份验证方法都没有检查令牌,或者至少除了TokenValidationParameters之外我没有提供它。

我认为它因Token组合而起作用,服务会将其分解以提取当前用户并将其插入Identity。

然而,当我致电userManager.GetUserId(user)时,它会返回null。

public string CurrentUser
{
    get
    {
        var user = accessor.HttpContext?.User;
        if (user != null)
            return userManager.GetUserId(user);
        return null;
    }
}

用户的内容如下:

S1 S2

我做错了什么?

屏幕截图声明(令牌创建)

S3

更新

Mohammed Noureldin的帮助下,我发现我的CurrentUser财产中没有声明。

[Authorize]放入我的控制器后,它开始工作了。 但是,我也需要它来处理匿名行为...... 有什么想法吗?

1 个答案:

答案 0 :(得分:1)

如果我正确理解您的问题,您将无法从User获取当前登录的Identity

您需要向Name添加ClaimsIdentity声明,该声明会自动转换为Name属性的Identity声明。

以下是一个例子:

var claims = new List<Claim>
{
    new Claim(ClaimTypes.Name, "SomeName or Id")
};

并在此列表中添加您需要的任何其他声明,然后创建ClaimsIdentity

ClaimsIdentity identity = new ClaimsIdentity(claims, "jwt");

UPDATE:

我之前没有注意到您尝试在授权过程中添加Claims(以及整个Identity)。这不是它应该如何。添加声明应该在身份验证内部进行,而不是授权。