0

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);

}
4

1 回答 1

1

自定义授权属性看起来正确。

由于您自己设置 cookie,我猜您没有使用内置的会员服务提供商。

如果您自己设置 cookie,您还需要读取 auth cookie 并在每个请求上设置 Identity 和 Principal 对象。否则,HttpContext.User.Identity.IsAuthenticated 将始终为 false,这似乎是您正在经历的。

于 2013-07-31T17:18:42.960 回答