Code Explorer
Code Explorer

Reputation: 65

Restricting access to action methods in controller in Asp.net MVC

I am new to Asp.net MVC web development and I developed one application using it. In my application I am using my own authentication and authorization check as follows: I create Login controller in that created Login action method like this

[HttpPost]
public ActionResult Login(LoginViewModel Info)
{
    if (ModelState.IsValid)
    {
        if (checking username and password exist in DB or not)
        {
            //Adding required values in session 
            Session["username"] = Info.Username;

            //Redirect to dashboard     
        }
        else
        {
            //not found redirect to login page
        }
    }
    return View();
}

Now when accessing action methods in Admin controller I used my "custom authorize" attribute for checking user is logged-in or not and have rights for method

public class AdminController : Controller
{
    [CustomAuthorize(ValidRole = "Admin")]
    public ActionResult Index()
    {
        return View();
    }
}

For this I override default AuthorizeAttribute like this

public class CustomAuthorize : AuthorizeAttribute
{
    // Custom property
    public string ValidRole { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext.Session["username"] == null)
        {
            //User is not logged-in so redirect to login page
            return false;
        }
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new RedirectToRouteResult(
        new RouteValueDictionary(
            new
            {
                controller = "Login",
                action = "Login"
            })
        );      
    }
}

This code works fine for me. My question that is there any better solution for checking whether user is logged-in or not and according to it redirect user to login or dashboard page so that user can't manipulate url and get access to functionality to which he is not authorized.

thanks in advance

Upvotes: 1

Views: 5342

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

My question that is there any better solution for checking whether user is logged-in or not and according to it redirect user to login or dashboard page so that user can't manipulate url and get access to functionality to which he is not authorized.

Yes, there's already a built-in method for doing this that does not rely on ASP.NET Sessions. It is called Forms Authentication.

You don't need to be writing any custom Authorize attributes. Once you verified the credentials of the user simply set the FormsAuthentication cookie:

if (checking username and password exist in DB or not)
{
    // Emitting forms authentication cookie
    FormsAuthentication.SetAuthCookie(Info.Username, false);

    //Redirect to dashboard     
}

and then simply use the built-in Authorize attribute to decorate your protected controller actions:

public class AdminController : Controller
{
    [Authorize(ValidRole = "Admin")]
    public ActionResult Index()
    {
        // At this stage the user is authenticated and has the role Admin.
        // You could get the current username using the User.Identity.Name property
        return View();
    }
}

Forms Authentication is stateless. It does not rely on any state on the server to track the currently authenticated user on the server. The information about the current user is contained in an encrypted forms authentication cookie that is sent along each request. This way you don't need to be thinking about handling complex scenarios when your application is hosted in a web farm in which case you would have needed to use distributed ASP.NET Sessions.

Upvotes: 2

Related Questions