TechnicalTophat
TechnicalTophat

Reputation: 1725

Custom authentication issues

I'm implementing a custom authentication in ASP.NET MVC, and I'm having issues redirecting to the login/register page if the user isn't logged in.

I'm using a global variable for IsAuthenticated, and if this is false I want to redirect all requests to the Account/LoginIndex controller. I don't want to violate DRY and add a filter or basic check in all the controllers, so is there an entry point where I can redirect to the action is the boolean evaluates to false? How would I do this? I had a look at ActionFilters but I don't know where I'd add it as an attribute. I also looked at filters AND modifying the global.asax file. None of this works. The controllers rely on the user being logged in (otherwise it's error central), so how would I do this? Thanks.

Upvotes: 0

Views: 55

Answers (1)

Sandeep Saran
Sandeep Saran

Reputation: 36

You can use Global filters and register AuthorizeAttribute as shown below

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new AuthorizeAttribute());
    }
}

Then in your controller that deals with login you should override Authorization Filter so that it does not require authorization

[OverrideAuthorization]
public class AccountController : Controller

You can also implement a custom class that inherits from AuthorizeAttribute if you need any custom behavior for authorization and then register the custom class through global filters.

Upvotes: 1

Related Questions