Search code examples
c#asp.net-coreasp.net-core-identity

ASP NET CORE Identity redirecting to Access Denied when logout


I am working with ASP.NET Core Identity. My app is configured to require authenticated users globally and Role based authorization is set on Controllers and Action methods as required. On my account controller I have set [Authorize(Roles = "Admin"] and on the Logout action of the account controller I used [Authorize] expecting that all Authorized users can access the logout action. But with [Authorize(Roles = "Admin"] set on the controller the user is redirected to Access Denied Route when logout is invoked unless he/she is in the admin role but if the [Authorize(Roles = "Admin"] is commented out it works for both admin and non admin users. How can I Allow all authorized users to access logout action? below is my code

[Authorize(Roles = "Admin")]
public class AccountController : Controller
{

    /*
    Rest of Code
    */

    [HttpPost, Authorize]
    public async Task<IActionResult> Logout()
    {

    }
}

Solution

  • As Martin Martin Costello says, you could add [AllowAnonymous] attribute at the Logout method.

    As far as I know, the action method's [AllowAnonymous] attribute will not affect other controller's actions. So this method will be security.

    Then you could put below codes inside the Logout method:

        [AllowAnonymous]
         public async Task<IActionResult> Logout(string returnUrl = null)
        {
            await _signInManager.SignOutAsync();
            _logger.LogInformation("User logged out.");
            if (returnUrl != null)
            {
                return LocalRedirect(returnUrl);
            }
            else
            {
                return RedirectToPage();
            }
        }