I want to customize my ASP .NET application's authentication and authorization (roles included) using my own logic. I'm using a JWT token. I do not want ASP .NET to check my token for me, I want to check the token myself and then override the authentication and Authorization with roles.
The steps I want:
- I want to implement Authentication and Authorization
- Then I want to retrieve the token.
- I want to implement my own logic wether the token is valid or not
- I want to tell ASP .Net whether the authentication has suceeded or not based on my logic.
What I have tried (Which is not completely overiding ASP .Net's Authentication method ):
builder.AddJwtBearer(o =>
{
// JWT Validation
o.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false,
ValidateIssuer = true,
ValidIssuers = new[] { "http://localhost:8080/realms/GT" },
ValidateIssuerSigningKey = true,
IssuerSigningKey = BuildRSAKey(publicKeyJWT),
ValidateLifetime = true
};
o.Events = new JwtBearerEvents()
{
OnMessageReceived = async c =>
{
if (c.Token == null)
{
c.NoResult();
c.Response.StatusCode = 500;
c.Response.ContentType = "text/plain";
await c.Response.WriteAsync("No token was provided");
return;
}
// custom logic to check token
// if true then Success
// else fail
BuildClaims(c.Principal); // roles claims included
return;
}
};
});
In the code I am calling the OnMessageReceived event, but the problem is that c.Token is null. Thus, I cannot retrieve the token using this method.
Is there a way to retreive the token using this method or is there another way to customize ASP .Net's authentication process with my requirements?