Search code examples
asp.net-mvcauthenticationauthorizationunauthorized

Attribute for only allow anonymous in ASP.Net MVC


I know that there is an attribute when a user must be authorize or not. You can also place [AllowAnonymous] above it. See also code below:

[Authorize] // only when the user is authorize
public class AccountController : Controller
{
    [HttpGet]
    [AllowAnonymous] // also when the user in not authorize.
    public ActionResult Login(string returnUrl = "")
    { /* Some code */ }

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    { /* Some code */ }
}

But is there also an attribute for allow anonymous only. For example: a login page only show when the user is not authorize?


Solution

  • I don't think there's an existing one, but there's no reason you can't roll your own. However, I would point out that it seems odd that you'd go to the extra effort to restrict content to an authenticated user:

    public class AnonymousOnly : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                 // Do what you want to do here, e.g. show a 404 or redirect
            }
        }
    }
    

    Then just decorate your class/method with this new attribute:

    [AnonymousOnly]
    public ActionResult Login(string returnUrl = "")
    {
        // code
    }