ASP MVC 5 Logged in User can still access Login an

2019-09-05 16:33发布

I have an ASP MVC 5 application and I've noticed that logged in user can still access the registration and login pages. I've also noticed that when a logged in user tries to access a controller action to which they are not authorized, they are redirected to the login page. This is confusing because the user is already logged in.

How do I fix this so that unauthorised redirects to some other 401 error page or view.

1条回答
爷的心禁止访问
2楼-- · 2019-09-05 17:28

On registration/login page, you can redirect logged users :

// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
    if (User.Identity.IsAuthenticated)
    {
        return RedirectToAction("Index", "Account");
    }
    // ...
}

And if you use role, you can override the AuthorizeAttribute

[AuthorizeRole(Roles="Admin")]
public ActionResult Admin()
{
//...
}

AuthorizeRoleAttribute.cs
Edit: Override HandleUnauthorizedRequest

public class AuthorizeRoleAttribute : AuthorizeAttribute
{
    public override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.User.Identity.IsAuthenticated
            // Check if user is in roles
            && Roles.Split(',').Any(filterContext.HttpContext.User.IsInRole))
        {
            // Not in any role change view
            filterContext.Result = new ViewResult
            {
                ViewName = "~/Views/Shared/UnauthorizedRole.cshtml"
            };
        }
        else{
            base.HandleUnauthorizedRequest(filterContext);
        }
    }
}
查看更多
登录 后发表回答