4

I'm using AddJwtBearer to use OAuth/OpenId authentication mechanism with my application. One of my need is to add a specific claim after the user is logged in (or the token gets refreshed).

Currently, I'm using the OnTokenValidated event, but the issue is that it gets called for each request and as I'm calling the database to retrieve the claim I want to add, it's pretty annoying. Especially now that I need to add another claim that will take more time to retrieve from the database.

What I'm looking for is a way to add custom claim only after the authentication, to avoid calling the database for every request.

ssougnez
  • 5,315
  • 11
  • 46
  • 79

1 Answers1

2

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 .

Douglas Gaskell
  • 9,017
  • 9
  • 71
  • 128
Nan Yu
  • 26,101
  • 9
  • 68
  • 148
  • Hi, the goal is basically to add claims to the token before it gets sent to the front end app, this way, the new claim will always be present in the token and I won't need to fetch the data everytime. If I understand your explanation correctly, the middleware is just a different technique than OnTokenValidated but will have the same effect ? – ssougnez Jun 12 '19 at 06:32
  • @ssougnez , yes ,you should add claims to token . Otherwise you need to add claims on each reqeust . – Nan Yu Jun 12 '19 at 06:34
  • I'll try the middleware right now but can you confirm that the middleware will run for every request, so it won't solve the issue. And as the claim I need to add cannot be retrieved by ADFD, there is basically no solution to add the claim to the token just once ? – ssougnez Jun 12 '19 at 07:02
  • You should add claims to token when issuing the token .That depends on which identity provider you are using . This link may help : https://stackoverflow.com/a/49202715/5751404 – Nan Yu Jun 12 '19 at 07:16