mohsinali1317
mohsinali1317

Reputation: 4425

Checking if the user is logged in asp.net mvc

In my application I am restricting some view and the user has to be logged in to view them. One way would be to check on every action if the user is logged in or not. But after a bit of research I found that asp.net MVS supports some global filter rules.

How do we use them? Ideally I would want to call a filter onBeforeAction and check if the user is logged in or not..

Is this a right approach? If yes, then can any body give me an example?

Upvotes: 0

Views: 1154

Answers (2)

Somdev Singh
Somdev Singh

Reputation: 47

Your [Authorize] will not work with the custom login. If you are using Form Authentication or other Authentication method than [Authorize] will work smoothly.

For custom login on success set

FormsAuthentication.SetAuthCookie([user name], false);

This will make your [Authorize] attribute to work properly.

And for logout use below statement

FormsAuthentication.SignOut();

If you follow the above solution than it will reduce your code as well as valid user check on before Action call.

Upvotes: 0

DavidG
DavidG

Reputation: 118947

The easiest way is to add the Authorize attribute to your controller or action methods. For example:

public class MyController : Controller
{
    //Normal action
    public ActionResult DoSomethingForAnyone() { }

    //Secured action
    [Authorize]
    public ActionResult DoSomethingOnlyForAuthorisedUsers() { }
}

Alternatively you can secure the entire controller and exclude actions you want to be accessible to anonymous users:

[Authorize]
public class SecureController : Controller
{
    public ActionResult DoSomething() { }

    [AllowAnonymous]
    public ActionResult DoSomethingForAnyone() { }
}

Upvotes: 3

Related Questions