What I'm looking for is a way to add custom claim only after the authentication
You can use Middleware which is invoked after authentication middleware :
UserClaimsMiddleware.cs:
public class UserClaimsMiddleware
{
private readonly RequestDelegate _next;
public UserClaimsMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext httpContext)
{
if (httpContext.User != null && httpContext.User.Identity.IsAuthenticated)
{
var claims = new List<Claim>
{
new Claim("SomeClaim", "SomeValue")
};
var appIdentity = new ClaimsIdentity(claims);
httpContext.User.AddIdentity(appIdentity);
await _next(httpContext);
}
}
}
public static class UserClaimsMiddlewareExtensions
{
public static IApplicationBuilder UseUserClaims(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<UserClaimsMiddleware>();
}
}
And register middleware in Configure
function of your Startup.cs
:
app.UseAuthentication();
app.UseUserClaims();
app.UseMvc();
to avoid calling the database for every request.
When server side get the API call with token , the AddJwtBearer
will decode token ,validate token and make user authenticated , you can add new claims either in OnTokenValidated
or in custom middleware . But the claims won't persist in next api calls unless you add the claims on each request .