Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authorization with Session variables in asp net mvc 5

So my project requirements changed and now I think I need to build my own action filter.

So, this is my current login controller:

 public class LoginController : Controller
{
    // GET: Login
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]

    public ActionResult Login(LoginViewModel model)
    {  
        string userName = AuthenticateUser(model.UserName, model.Password);
        if (!(String.IsNullOrEmpty(userName)))
        {
            Session["UserName"] = userName;
            return View("~/Views/Home/Default.cshtml");
        }

        else
        {
            ModelState.AddModelError("", "Invalid Login");
            return View("~/Views/Home/Login.cshtml");
        }
    }

    public string AuthenticateUser(string username, string password)
    {
        if(password.Equals("123")
            return "Super"
        else
            return null;
    }

    public ActionResult LogOff()
    {
        Session["UserName"] = null;
        //AuthenticationManager.SignOut();
        return View("~/Views/Home/Login.cshtml");
    }
}

And this is my action filter attempt:

public class AuthorizationFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (HttpContext.Current.Session["UserName"] != null)
        {
            filterContext.Result = new RedirectToRouteResult(
                   new RouteValueDictionary{{ "controller", "MainPage" },
                                      { "action", "Default" }

                                     });
        }
        base.OnActionExecuting(filterContext);
    }
}

I have already added it to FilterConfig, but when I login it does not load Default.cshtml it just keeps looping the action filter. The action result for it looks like this:

//this is located in the MainPage controller

 [AuthorizationFilter]
    public ActionResult Default()
    {
        return View("~/Views/Home/Default.cshtml");
    }

So, what would I need to add in order to give authorization so only authenticated users can view the application´s pages? Should I use Session variables or is there another/better way of doing this using? I am pretty much stuck with AuthenticateUser(), since what happens there now is just a simple comparison like the one we have there now.

Thank you for your time.

like image 674
jiggergargle Avatar asked Feb 10 '23 02:02

jiggergargle


2 Answers

Create an AuthorizeAttribute with your logic in there:

public class AuthorizationFilter : AuthorizeAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
            || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
        {
            // Don't check for authorization as AllowAnonymous filter is applied to the action or controller
            return;
        }

        // Check for authorization
        if (HttpContext.Current.Session["UserName"] == null)
        {
            filterContext.Result = new HttpUnauthorizedResult();
        }
    }
}

As long as you have the Login URL Configured in your Startup.Auth.cs file, it will handle the redirection to the login page for you. If you create a new MVC project it configures this for you:

public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseCookieAuthentication(
            new CookieAuthenticationOptions {

                    // YOUR LOGIN PATH
                    LoginPath = new PathString("/Account/Login")
            }
        );
    }
}

Using this you can decorate your controllers with [AuthorizationFilter] and also [AllowAnonymous] attributes if you want to prevent the authorization from being checked for certain Controllers or Actions.

You might want to check this in different scenarios to ensure it provides tight enough security. ASP.NET MVC provides mechanisms that you can use out of the box for protecting your applications, I'd recommend using those if possible in any situation. I remember someone saying to me, if you're trying to do authentication/security for yourself, you're probably doing it wrong.

like image 86
Luke Avatar answered Feb 14 '23 12:02

Luke


Since your attribute is added to the FilterConfig, it will apply to ALL actions. So when you navigate to your MainPage/Default action it will be applying the filter and redirecting you to your MainPage/Default action (and so on...).

You will either need to:

  • remove it from the FilterConfig and apply it to the appropriate actions / controllers
  • or add an extra check in the filter so that it doesn't redirect on certain routes
like image 30
Will Smith Avatar answered Feb 14 '23 10:02

Will Smith