Reputation: 1199
I know if I have a method and I only want Authenticated
uses to use it I can mark it with:
[Authorize]
If I have a method where I want both authorized
and non authorized
people to use it I can mark a method with:
[AllowAnonymous]
If I have a method where only Anonymous users
can use and not Authenticated users
how can I do this?
Upvotes: 1
Views: 53
Reputation: 49123
You can use this UnAuthenticatedOnlyAttribute
:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class UnAuthenticatedOnlyAttribute : ActionFilterAttribute
{
public string RedirectTo { get; set; } = "/Error";
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var user = filterContext.HttpContext.User;
if (user != null && user.Identity != null && user.Identity.IsAuthenticated)
filterContext.Result = new RedirectResult(RedirectTo);
}
}
Usage:
[UnAuthenticatedOnly(RedirectTo = "/Main")]
public ActionResult Login()
{
// ...
}
Upvotes: 1