Hello,
I am building a very simple application. Angular2 client. Asp.net Core Web API to provide the data to the client. I am using Asp.net Core Identity to store user access and do the authentication part. I am using Jwt tokens to do the Authorization part.
It seems to work, but I don't understand how. What is the best practice of having Identity and Jwt work together? Identity also has to concept of Claims. So does Jwt.
In my login method, I have something like this.
var result = await this._signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure: false);
This authenticates the user based on username and password. So far so good. If login was successful, I will now go ahead and created a bearer token. In my case Jwt. That looks something like this.
var identity = new ClaimsIdentity(new GenericIdentity(userName, "Token"),
new[]
{
new Claim("Role", isAdmin ? "Admin" : "User")
});
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, userName),
new Claim(JwtRegisteredClaimNames.Jti, await jwtOptions.JtiGenerator()),
new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),
identity.FindFirst("Role")
};
var jwt = new JwtSecurityToken(
jwtOptions.Issuer,
jwtOptions.Audience,
claims,
jwtOptions.NotBefore,
jwtOptions.Expiration,
jwtOptions.SigningCredentials);
return new JwtSecurityTokenHandler().WriteToken(jwt);
So, now the client has a token it can use to get access to the web API. It works. During a request from the client, on the server, I can get the user's name for example.
return this.User.Claims.FirstOrDefault(p => p.Type == ClaimTypes.NameIdentifier)?.Value;
How does that work? Is the token processed in one of the Middlewares? Which one? How?
Thanks
--tolga