asp.netasp.net-web-apiasp.net-identityidentityopeniddict

How to make redirect after logout using OpenIddict?


I have logout endpoint that invalidates user token and should perform redirect to login page after logging user out

[HttpGet("logout")]
    [HttpPost("logout")]
    [ApiVersion("1.0")]
    public async Task<IActionResult> Logout(CancellationToken cancellationToken)
    {
        var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        if (!result.Succeeded)
        {
            logger.LogError("User is not authenticated");
            return BadRequest("User is not authenticated.");
        }
        
        var username = result.Principal.GetClaim(Claims.Username);
        var user = await userManager.FindByNameAsync(username);
        if (user is null)
        {
            return Unauthorized();
        }
        
        await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        
        await authorizationService.InvalidateToken(user, cancellationToken);
        
        return SignOut(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
    }

I tried to add RedirectUri to AuthenticationProperties but it doesn't work

 var properties = new AuthenticationProperties
        {
            RedirectUri = postLogoutRedirectUri
        };

        return SignOut(properties, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);

Solution

  • It turned out to be very simple, just provide post_logout_redirect_uri parameter as query or body parameter:

    /logout?post_logout_redirect_uri=https://example.com/login

    OpenIddict will handle it automatically and redirect to specified uri after logout. Also, you should add this uri to PostLogoutRedirectUris column in OpenIddictApplications table, and add the following line in the OpenIddict configuration:

    services.AddOpenIddictCoreWithEntityFramework()
                .AddServer(options =>
                {
                    options.UseAspNetCore()         
                         .EnableLogoutEndpointPassthrough();
                }