Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 206
H. Pauwelyn Avatar asked Nov 04 '15 11:11

H. Pauwelyn


1 Answers

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
}
like image 149
ediblecode Avatar answered Oct 21 '22 11:10

ediblecode