user1534664
user1534664

Reputation: 3418

user isn't authenticated in custom authorize attribute

I've made my own authorize attribute, and this is what it looks like

public class RedirectAuthorize : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            filterContext.Result = new RedirectToRouteResult(new
            RouteValueDictionary(new { controller = "NotExist" }));            
        }
    }
}

So if the user isn't authenticated, I want them to get redirected to the NotExist controller. I've debugged and it seems that unauthorized users get in the if clause, which is correct. But I've also tried doing this with logged in users, and they get in the if clause as well which is wrong.

I dont understand why this is happening. It makes me hesitate about whether my log-in didnt work. Is this the right way of logging a user in?

FormsAuthentication.SetAuthCookie(acc.username, false);

I've never made a log-in system in asp.net mvc before, so please tell me what I'm doing wrong.

Edit:

It seems that the default [Authorized] attribute isn't working either... I really think the problem lays in the log in:

[HttpPost]
public ActionResult Login(User acc)
{
    if(ModelState.IsValid)
    {
        if (Validate(acc.username, acc.password))
        {
            FormsAuthentication.SetAuthCookie(acc.username, false);
            return RedirectToAction("Index", "System");
        }
    }

    ModelState.AddModelError("IncorrectDetails", "Wrong details. Please try again.");
    return View(acc);

}

Upvotes: 0

Views: 1627

Answers (1)

Andy T
Andy T

Reputation: 9901

The custom authorize attribute looks correct.

Since you are setting the cookie yourself I would guess you are not using the built-in membership provider.

If you set the cookie yourself, you also need to read the auth cookie and set the Identity and Principal objects on each request. Otherwise, HttpContext.User.Identity.IsAuthenticated will always be false, which seems to be what you are experiencing.

Upvotes: 1

Related Questions