Question

Is there an attribute in MVC5 that would allow me to deny authorized users to access certain pages?

I'm trying to restrict Authorized users from viewing certain pages such as the registration page.

Currently users can browse to my sign up page if they know the URL even when they're registered.

I thought there would have been an attribute something like [DenyAuthorized], or is there another method to do this?

I think this is a fairly common requirement and that I'm probably not implementing something correctly.

I have written a short attribute and it does work, however I'm not convinced it's the best way to do it:

public class DenyAuthorized : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            if (filterContext.HttpContext.Request.UrlReferrer != null)
            {
                filterContext.Result = new RedirectResult(filterContext.HttpContext.Request.UrlReferrer.AbsoluteUri);
            }
            else
            {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { action = "Index", controller = "Home", area = "", }));
            }
        }
    }
}

Are there any better methods to do this?

Was it helpful?

Solution

The best way of doing is to check the login status of user in Login/Register action and redirecting them to dashboard/home/landing page if user has signed in.

That is how it should be.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top