I've an application that requests a token when the user signs in. That token is then passed with the following header:
Authorization: Bearer <TOKEN>
I've the following code on my 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;
});
}
To create tokens when the user sign in, I've TokenProvider
service:
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
};
}
}
As you can see, TokenValidationParameters
used in AddJwtBearer
is provided by the code above GetValidationParameters
.
My first perception on this, was that none of the startup
authorization/authentication methods checked for the token, or at least I'm not providing it besides the TokenValidationParameters
.
I assumed that it worked because of the Token composition and the service would decompose it to extract the current user and insert it into Identity.
However, when I call userManager.GetUserId(user)
it returns null.
public string CurrentUser
{
get
{
var user = accessor.HttpContext?.User;
if (user != null)
return userManager.GetUserId(user);
return null;
}
}
The content of user is the following:
What am I doing wrong?
Screenshot Claims (Token creation)
Update
With the help of Mohammed Noureldin I've discovered that I didn't have claims in my CurrentUser
property.
After putting [Authorize]
in my controller it started working.
However, I need it to work on anonymous actions too...
Any idea?
If I understood your problem correctly, you are not able to get who is the current logged in User
from the Identity
.
You need to add Name
claim to your ClaimsIdentity
, which will automatically be translated to Name
property of Identity
property.
Here is an example:
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, "SomeName or Id")
};
and add any other claim you need to this list, and then create your ClaimsIdentity
:
ClaimsIdentity identity = new ClaimsIdentity(claims, "jwt");
I did not notice before that you are trying to add Claims
(and the whole Identity
) inside your authorization process. That is not how it should be. Adding claims should happen inside authentication, not authorization.