IdentityServer4 - Redirect to MVC client after Logout
If anyone is using the Scaffolding (they use the Razor Page files), here is how to fix it according to the answer of Akhilesh:
In Areas\Identity\Pages\Account\Logout.cshtml:
First, add IIdentityServerInteractionService
service:
IIdentityServerInteractionService _interaction;
public LogoutModel(SignInManager<IdentityUser> signInManager, ILogger<LogoutModel> logger, IIdentityServerInteractionService _interaction)
{
_signInManager = signInManager;
_logger = logger;
this._interaction = _interaction;
}
You may need to add support for OnGet()
, logic maybe different depends on your case, in my case, Get or Post does not matter:
public async Task<IActionResult> OnGet(string returnUrl = null)
{
return await this.OnPost(returnUrl);
}
Add the LogoutId logic in OnPost:
public async Task<IActionResult> OnPost(string returnUrl = null)
{
await _signInManager.SignOutAsync();
_logger.LogInformation("User logged out.");
var logoutId = this.Request.Query["logoutId"].ToString();
if (returnUrl != null)
{
return LocalRedirect(returnUrl);
}
else if (!string.IsNullOrEmpty(logoutId))
{
var logoutContext = await this._interaction.GetLogoutContextAsync(logoutId);
returnUrl = logoutContext.PostLogoutRedirectUri;
if (!string.IsNullOrEmpty(returnUrl))
{
return this.Redirect(returnUrl);
}
else
{
return Page();
}
}
else
{
return Page();
}
}
There is no problem in your Config.cs or in the MVC controller.
Go to your IdentityServer4 Application then inside AccountController's Logout [HttpPost] method, do the following changes:
public async Task<IActionResult> Logout(LogoutViewModel model)
{
...
//return View("LoggedOut", vm);
return Redirect(vm.PostLogoutRedirectUri);
}
This will redirect the user back to MVC application (in your case).
There is a better way to do this: You can set these options from AccountOptions.cs as follows:
public static bool ShowLogoutPrompt = false;
public static bool AutomaticRedirectAfterSignOut = true;