Search code examples
asp.net-coreidentityserver4access-tokenopenid-connectblazor

Identity Server 4 : Custom OIDC login callback to store tokens in a store


I'm currently building a Blazor app that needs authentication and retrieve acces_token to access an API. I'm also using refresh_token to avoid user relogin when browsing.

My current way to manage it is to register a custom httpClient in dependency injection system, retrieve HttpContext to check for access_token and if not good, call manually idsrv4 to retrieve new access & refresh tokens

The main issue is that by doing so, I cannot write into httpContext the new values (response has already begin) so I'll have to do it everytime, losing advantages of token lifetime.

My goal is to store all user informations & token informations within a custom store. To do so, I'll have to handle the point when tokens are retrieved, but I can't find a god place to fit in as callback ?

I've already tried the Events property within the AddOpenIdConnect options, but it doesn't seems any of them can fit my needs ?

Where can I put my custom callback logic after login ?


Solution

  • If you want to get and store the access token after client app get the access token , you can use OnTokenResponseReceived event :

    options.Events = new OpenIdConnectEvents
    {
    
        OnTokenResponseReceived = ctx =>
        {
            var accessToken = ctx.TokenEndpointResponse.AccessToken;
    
            var idToken = ctx.TokenEndpointResponse.IdToken;
    
            return Task.CompletedTask;
        },
    };