无法从JWT令牌获取版权声明数据

时间:2018-12-07 09:15:06

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

我将用户名和密码存储到“ JWT令牌声明”中,如下所示:-

 var claims = new Claim[]
             {
                  new Claim("Id", id.ToString()),
            new Claim(JwtRegisteredClaimNames.Email, email),
            new Claim(JwtRegisteredClaimNames.Acr, roleName)
             };
JwtSecurityToken tokeOptions = new JwtSecurityToken(
        issuer: Constant.JsonTokenMessage.Issuer,
        audience: Constant.JsonTokenMessage.Audience,
        claims: claims,
        expires: DateTime.Now.AddMinutes(5),
        signingCredentials: signinCredentials
    );

但是当我尝试使用下面的代码来获取它时,它给了我空的声明集合,因此对象引用未设置为实例错误。

this.User.Claims.First(i => i.Type == "Id").Value.

Startup.cs ConfigureService方法代码如下

 SymmetricSecurityKey secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SuperSecretKey@123"));
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            })
             .AddJwtBearer(x =>
             {
                 x.Events = new JwtBearerEvents
                 {
                     OnTokenValidated = context =>
                     {
                         var userService = context.HttpContext.RequestServices.GetRequiredService<IUserService>();
                         var userId = Convert.ToInt32( context.Principal.Identity.Name);
                         var user = userService.GetUser(userId);
                         if (user == null)
                         {
                            // return unauthorized if user no longer exists
                            context.Fail("Unauthorized");
                         }
                         var httpContxt = httpContextAccessor.HttpContext;
                         httpContxt.Items["AuthenticationTokenUser"] = user;
                         httpContxt.Items["AuthenticationAccessTokenValid"] = true;
                         return Task.CompletedTask;
                     }
                 };
                 x.RequireHttpsMetadata = false;
                 x.SaveToken = true;
                 x.TokenValidationParameters = new TokenValidationParameters
                 {
                     ValidateIssuerSigningKey = true,
                     IssuerSigningKey = secretKey,
                     ValidateIssuer = false,
                     ValidateAudience = true,
                     ValidAudience = "Example",
                     ValidIssuer= "Example"

                 };
             });

我们非常感谢您的帮助。

0 个答案:

没有答案