BuddyJoe
BuddyJoe

Reputation: 71101

Custom Authentication and ASP.NET MVC

I have an internal web app being built in ASP.NET 4. We are stuck with using an authentication API built by another team. If a user to the site is authenticated successfully for the site I would like to give them access to the entire site.

In ASP.NET WebForm days I just used to keep a custom User object in session. If that object was null I knew the user wasn't authenticated. Is there a similar but improved method for this in MVC. I don't want to have to build my own provider of the ASP.NET Membership model if possible. What is the simplest way of doing this?

Upvotes: 27

Views: 49021

Answers (5)

yogihosting
yogihosting

Reputation: 6292

You can do the Session Authentication by simply putting a session variable value when the login is successful. Eg

public ActionResult Index(Models.Login login)
    {
        if (ModelState.IsValid)
        {
            Dal.Login dLogin = new Dal.Login();
            string result = dLogin.LoginUser(login);
            if (result == "Success")
                Session["AuthState"] = "Authenticated";
        }
        return View();
    }

Now the trick is that you should have a common layout page of all the views to which you have to check for authentication. And in this layout page just do a razor check like this -

<body>
    @if (Session["AuthState"] != "Authenticated")
    {
        Response.Redirect("~/login");
    }
    // other html
</body>

I have been using this method in my application admin panel.

Upvotes: -2

Jatin patil
Jatin patil

Reputation: 4288

You can use Forms Authentication in conjuction with Authorize attibute as follows,

To restrict access to a view :

Add the AuthorizeAttribute attribute to the action method declaration, as shown below,

[Authorize]
public ActionResult Index()
{
    return View();
}

Configuring Forms Authentication in web.config

<authentication mode="Forms">
     <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>

Login Post Action: Set Authentication cookie if user is valid

[HttpPost]
public ActionResult Login(User model, string returnUrl)
{
        //Validation code

        if (userValid)
        {
             FormsAuthentication.SetAuthCookie(username, false);
        }
}

Log off Action:

public ActionResult LogOff()
{
    FormsAuthentication.SignOut();
    return RedirectToAction("Index", "Home");
}

Upvotes: 45

volpav
volpav

Reputation: 5128

You probably want to have a custom authorization filter. Here's an example: Custom filters in MVC. You can then apply this filter globally on app start (using RegisterGlobalFilters).

public class LegacyAuthorize : AuthorizeAttribute
{
  public override void OnAuthorization(HttpActionContext actionContext)
  {
    if (HttpContext.Current.Session["User"] == null)
      base.HandleUnauthorizedRequest(actionContext);
  }
}

Then in your global.asax you'd have something like this:

GlobalFilters.Filters.Add(new LegacyAuthorize());

Upvotes: 5

Daniele
Daniele

Reputation: 1938

You can try with something like this:

FormsAuthentication.SetAuthCookie(username, rememberMe);

to set the cookie for authenticated user, then just use the [Authorize] attribute on the Controller or Action that need authentication.

Try googling on the subject for further info, you will find a lot of stuff on authentication and authorization in MVC.

Upvotes: 4

Solmead
Solmead

Reputation: 4199

Everything you could do in forms you can do in MVC, just set the session variable in the controller login action.

Or you can do this: In the login action add formsauthentication.setauthcookie("username")

After this any action with the [Authorize] keyword will allow the current user in.

Upvotes: 1

Related Questions