Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

default login url on HttpUnauthorizedResult in asp.net mvc

I have written a custom AuthorizeAttribute which has the following condition in asp.net mvc3 application:

public override void OnAuthorization(AuthorizationContext filterContext)
{     
    //auth failed, redirect to Sign In
    if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
    {
       filterContext.Result = new HttpUnauthorizedResult();
    }
}

And in my web.config, i have:

<authentication mode="Forms">
  <forms loginUrl="~/User/SignIn" timeout="2880" />
</authentication>

On authentication fail, it redirects to "/Account/Login" page by default.

How do i change this default redirect url and redirect it to "/User/SignIn"?

The screenshot shows the clear view of what i am trying to say..HttpUnauthorizedresult image

Though i have set '/User/SignIn', it redirects to '/Account/Login'

like image 489
Prasad Avatar asked May 16 '11 09:05

Prasad


3 Answers

I am not sure whether i can add this as an answer. But this may help others who were having this related issue.

I got the solution after a struggle. I have added WebMatrix.WebData reference recently, which seems to be the real culprit of this issue. This can be handled by adding the key to your config file:

<add key="loginUrl" value="~/User/SignIn" />
like image 146
Prasad Avatar answered Oct 19 '22 23:10

Prasad


You should be modifying the root one for loginUrl.

i have created AuthorizationAttribute... it's redirecting properly e.g.

<authentication mode="Forms">
    <forms loginUrl="~/Authenticate/SignIn" timeout="2880"/>
</authentication>

and my attribute is:

public class AuthorizationAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);

        if (!filterContext.HttpContext.User.Identity.IsAuthenticated) 
        {
            filterContext.Result = new HttpUnauthorizedResult();
        }
    }
}

and apply attribute to any method of your controller as necessary...

[AuthorizationAttribute()]
public ActionResult Index()
{
    return View();
}
like image 35
Usman Masood Avatar answered Oct 20 '22 00:10

Usman Masood


I recently had this problem and found it was because I had the WebMatrix.dll referenced in my project.

Removing this DLL fixed the issue

see here What is the PreserveLoginUrl appSetting key/value in an ASP.NET MVC application?

like image 40
Keeno Avatar answered Oct 19 '22 23:10

Keeno