Reputation: 620
I'm trying to configure an authentication in some application that will consume the login validation from another system. Basically, I get a token with the users information, and I have to map it to my database, because the user it was already authenticated. We're doing it with using jwt tokens.
So here's the problem:
The token I'm getting doesn't have "iat" field, and AspNetCore seems to reject the token without that field.
Is there a way to configure the authentication to ignore that field?
Here is the token structure:
{
"alg": "HS512"
}
{
"sub": [mysub],
"user": { ... },
"exp": [timestamp]
}
And here's the configuration:
...
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuerSigningKey = false,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
...
Upvotes: 0
Views: 993
Reputation: 59
Edit: An earlier version of this answer mixed up iat
and nbf
. The answer has been rewritten accordingly.
I tried reproducing your issue in an empty project, and was successfully able to validate a token with the structure you outlined in your question (so without the iat
claim).
Setup I used to get this to work:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(o =>
{
o.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = false,
ValidateIssuer = false,
ValidateAudience = false,
SignatureValidator = (t, p) => new JwtSecurityToken(t)
};
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
[Authorize]
[Route("debug")]
public class DebugAuthController : ControllerBase
{
[HttpGet]
public IActionResult Get() => Ok(User.Claims.Single(c => c.Type == "user").Value);
}
I used the following token for testing: eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJteXN1YmplY3QiLCJ1c2VyIjp7Im5hbWUiOiJTdGFja092ZXJmbG93In0sImV4cCI6MTU5MDk5NzMyNn0.FVFl6gDYOrmzj7_6OqHPTxU3mfQWs864u7fBLM5ThuM
It's worth double-checking to see if you're calling both UseAuthentication
and UseAuthorization
in ConfigureServices
, and that you're calling them in that order.
Note: Sample code provided disables virtually all validation checks on the JWT for testing purposes. Do not use this code as-is unless you know what you're doing!
Upvotes: 1