Search code examples
asp.net-coreopeniddict

How to set refresh token in cookies for OpenIddict Asp.Net Core


I'm learning OpenIddict follow some samples of them but i didn't find how to set response refresh token in cookies and use the cookie to authenticate. The current behavior I make it work is the Exchange endpoint takes refresh_token in request body and return new access_token and refresh_token in response body

I have success setting up some basic authorization controller endpoints, I just want to use http-only cookies for storing refresh_token. I can't find a way to change this behavior in openiddict document


Solution

  • use this below code to handle token:

    public class CustomTokenEndpointHandler : OpenIddictServerEvents
    {
        public override Task ProcessSignIn(OpenIddictServerEvents.ProcessSignInContext context)
        {
            var response = context.Transaction.Response;
    
            // Set the refresh token in an HTTP-only cookie
            context.HttpContext.Response.Cookies.Append(
                "refresh_token",
                response.RefreshToken,
                new CookieOptions
                {
                    HttpOnly = true,
                    Secure = true,
                    SameSite = SameSiteMode.Strict,
                    Expires = DateTimeOffset.UtcNow.AddDays(14)
                });
    
            // Remove the refresh token from the response
            response.RemoveParameter(OpenIddictConstants.Parameters.RefreshToken);
    
            return Task.CompletedTask;
        }
    }
    

    Override the default behavior to read the refresh token from the cookie:

    public class CustomTokenExchangeHandler : OpenIddictServerEvents
    {
        public override async Task ProcessAuthentication(OpenIddictServerEvents.ProcessAuthenticationContext context)
        {
            // Check if the request is for token exchange and contains a refresh token grant type
            if (context.Request.IsTokenRequest() && context.Request.IsRefreshTokenGrantType())
            {
                // Read the refresh token from the cookie
                if (context.HttpContext.Request.Cookies.TryGetValue("refresh_token", out var refreshToken))
                {
                    context.Request.RefreshToken = refreshToken;
                }
                else
                {
                    context.Reject(
                        error: OpenIddictConstants.Errors.InvalidGrant,
                        description: "The refresh token is missing.");
                }
            }
    
            await base.ProcessAuthentication(context);
        }
    }
    

    now register the handle in program.cs file