Claims Identity .NET CORE 3.0 API JWT

不打扰是莪最后的温柔 提交于 2021-01-29 10:17:05

问题


I'm trying to develop a web API on .NET CORE 3.0 but I can't get userId from the controller

this is my StartUp

RSAParameters keyParams = RsaKeyUtils.GetKeyParameters("jwt_key.conf");
        var key = new RsaSecurityKey(keyParams);

        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    IssuerSigningKey = key,
                    ValidAudience = GappedAuthSettings.TokenAudience,
                    ValidIssuer = GappedAuthSettings.TokenIssuer,
                    ValidateIssuerSigningKey = true,
                    ValidateLifetime = true,
                    RequireSignedTokens = true,
                    ClockSkew = TimeSpan.FromMinutes(0)
                };
            });

This is how issue a JWT token :

 private string GetToken(string userEmail, DateTime? expires, IEnumerable<Claim> claims)
    {
        var handler = new JwtSecurityTokenHandler();

        var identity = new ClaimsIdentity(new GenericIdentity(userEmail, "Auth"), claims);

        var securityToken = handler.CreateToken(new SecurityTokenDescriptor
        {
            Issuer = this.tokenOptions.Issuer,
            Audience = this.tokenOptions.Audience,
            SigningCredentials = this.tokenOptions.SigningCredentials,
            Subject = identity,
            Expires = expires,
            IssuedAt = DateTime.UtcNow
        });

        return handler.WriteToken(securityToken);
    }

And when I try to read it claimsIdentity returns an object with null properties

    protected string GetUserId()
    {
        var claimsIdentity = this.User.Identity as ClaimsIdentity;
        var userId = claimsIdentity.FindFirst("userId")?.Value;

        if (userId != null)
        {
            return userId;
        }

        return null;
    }

IMG


回答1:


Here is a working demo like below:

1.appsettings.json:

"Jwt": {
   "Key": "ThisismySecretKey",
   "Issuer": "Test.com"
}

2.Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters()
        {
            ValidIssuer = Configuration["Jwt:Issuer"],
            ValidAudience = Configuration["Jwt:Issuer"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])),

            ValidateIssuerSigningKey = true,
            ValidateLifetime = true,
            RequireSignedTokens = true,
            ClockSkew = TimeSpan.FromMinutes(0)
        };
    });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseHttpsRedirection();          
    app.UseRouting();

    app.UseAuthentication();   //be sure to add this line
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

3.Controller:

[Route("api/[controller]")]
public class ValuesController : ControllerBase
{
    private IConfiguration _config;
    public ValuesController(IConfiguration config)
    {
        _config = config;
    }
    [HttpGet]
    public string Get()
    {
        var claim = new[]
        {
            new Claim("userId", "1")
        };
        var data = GetToken("np@hotmail.com", null, claim);
        return data;
    }
    [HttpGet]
    private string GetToken(string userEmail, DateTime? expires, IEnumerable<Claim> claims)
    {    
        var handler = new JwtSecurityTokenHandler();           
        var identity = new ClaimsIdentity(new GenericIdentity(userEmail, "Auth"), claims);

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

        var securityToken = handler.CreateToken(new SecurityTokenDescriptor
        {
            Issuer = _config["Jwt:Issuer"],
            Audience = _config["Jwt:Issuer"],
            SigningCredentials = credentials,
            Subject = identity,
            Expires = DateTime.Now.AddMinutes(120),
            IssuedAt = DateTime.UtcNow
        });
        return handler.WriteToken(securityToken);
    }
}

4.The Test method(Be sure to add [Authorize]):

[Route("api/[controller]")]
public class TestController : Controller
{       
    [Authorize]
    [HttpGet]
    public string Get()
    {
        var claimsIdentity = this.User.Identity as ClaimsIdentity;
        var claim = claimsIdentity.Claims;
        // or
        var data = claimsIdentity.FindFirst("userId").Value;
        return data;
    }
}

5.Test Procedure:

First,you need to get the token from GetToken method.

Then,call the test method with Authorization type Bearer Token.

Finally,you could get the claim.



来源:https://stackoverflow.com/questions/60225690/claims-identity-net-core-3-0-api-jwt

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