locked
Make it easier to validate if the same user or not in relation to DRY RRS feed

  • Question

  • User-1187675394 posted

    Goal:
    Make it easier to validate if the same user or not in relation to DRY.

    Problem:
    Every time when you go to the next page by using Actionresult you have to add a

            if (Session["UserID"] != null)  

    in every actionresult's content in order to make a validation.

    Question:
    Is there another approach in order to make it easier and better than today?

    My idea is to use this validation on top of the ActionResult

    Propose (is it possibly to do it?)

    [validation]
        public ActionResult UserDashBoard()  
        {  
               return View();  
        } 

    And not like this today:

        public ActionResult UserDashBoard()  
        {  
            if (Session["UserID"] != null)  
            {  
                return View();  
            } else  
            {  
                return RedirectToAction("Login");  
            }  
        } 

    The source that I am using is from this page.

    https://www.c-sharpcorner.com/article/simple-login-application-using-Asp-Net-mvc/

    Thank you!

    Thursday, June 6, 2019 1:05 PM

Answers

  • User-821857111 posted

    The article is not very good. You shouldn't use Session to manage authentication. You should use the formal authentication management APIs for whichever version of ASP.NET you are using. Then you can use the [Authorize] attribute on actions or controllers.

    If you are using ASP.NET Core, you can borrow the code from this Razor Pages example that shows how to implement simple cookie-based authentication properly: https://www.mikesdotnetting.com/article/335/simple-authentication-in-razor-pages-without-a-database

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 6, 2019 1:17 PM
  • User753101303 posted

    Hi,

    You could actually just delete this and use the same idea than the out of the box https://docs.microsoft.com/en-us/previous-versions/aspnet/dn896549(v%3Dvs.108) extension method.

    The implementation would check the Session value and would get it from the db if not found any more. This way you are back as having something that works as long as the user is authenticated rather than depending on the browser session.

    Plus if you later decide to move away from your custom authentication scheme, the code will be basically unchanged (you'll just switch to this "out of the box" extension method).

    You can apply the same general pattern for most if not all session variables in short :
    - avoid to load a session variable at some point and consume it elsewhere in which case you need to deal with what happen when the browser session expires
    - instead expose this behind a "facade". This way you can "cache" this value to a session variable and it will be just (re)loaded as needed
    and your app doesn't have to care any more where it actually comes from and even if it comes from Session

    Edit: ah it doesn't even use the basic out of the box authentication stuff provided out of the box by ASP.NET. Also I just noticed this is in the ASP.NET Core forum. You do have a leaning curve but consider to use https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity-custom-storage-providers?view=aspnetcore-2.2

    (IMO it's best to start here as it alllows to likely better grasp that you don't need all the bells and whiste and can start with something simple and add stuff as needed - the default implementation already implements much more). Hopefully I'll perhaps end up by having my own blog/programming site and starting with a custom implementation with really the minial amount of work you need to get started with ASP.NET Identity would be likely one thing I would find useful).

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 6, 2019 1:20 PM
  • User-1764593085 posted

    Hi sakuradata,

    It seems  that the tutorial is for asp.net MVC, do you use asp.net or asp.net core MVC?

    In asp.net core, you could custom an action filter to validate session before the action executes.

    1.Create a ValidateUserActionFilter:

    public class ValidateUserActionFilter : ActionFilterAttribute
        {
            public override async void OnActionExecuting(ActionExecutingContext context)
            {
                //replace below code to get your session data
                var name = context.HttpContext.Session.GetString("UserName");
                if(name == null)
                {
                    context.Result = new RedirectResult("/Identity/Account/Login");
                    await context.Result.ExecuteResultAsync(context);
                }
                base.OnActionExecuting(context);
            }
    
        }

    2.Use it as Attribute:

    [ValidateUserActionFilter]
    public ActionResult UserDashBoard()  
        {  
               return View();  
        } 

    If you use asp.net instead of asp.net core ,refer to 

    asp.net MVC custom action filters

    Redirect From Action Filter Attribute

    Best Regards,

    Xing

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, June 7, 2019 2:30 AM

All replies

  • User-821857111 posted

    The article is not very good. You shouldn't use Session to manage authentication. You should use the formal authentication management APIs for whichever version of ASP.NET you are using. Then you can use the [Authorize] attribute on actions or controllers.

    If you are using ASP.NET Core, you can borrow the code from this Razor Pages example that shows how to implement simple cookie-based authentication properly: https://www.mikesdotnetting.com/article/335/simple-authentication-in-razor-pages-without-a-database

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 6, 2019 1:17 PM
  • User753101303 posted

    Hi,

    You could actually just delete this and use the same idea than the out of the box https://docs.microsoft.com/en-us/previous-versions/aspnet/dn896549(v%3Dvs.108) extension method.

    The implementation would check the Session value and would get it from the db if not found any more. This way you are back as having something that works as long as the user is authenticated rather than depending on the browser session.

    Plus if you later decide to move away from your custom authentication scheme, the code will be basically unchanged (you'll just switch to this "out of the box" extension method).

    You can apply the same general pattern for most if not all session variables in short :
    - avoid to load a session variable at some point and consume it elsewhere in which case you need to deal with what happen when the browser session expires
    - instead expose this behind a "facade". This way you can "cache" this value to a session variable and it will be just (re)loaded as needed
    and your app doesn't have to care any more where it actually comes from and even if it comes from Session

    Edit: ah it doesn't even use the basic out of the box authentication stuff provided out of the box by ASP.NET. Also I just noticed this is in the ASP.NET Core forum. You do have a leaning curve but consider to use https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity-custom-storage-providers?view=aspnetcore-2.2

    (IMO it's best to start here as it alllows to likely better grasp that you don't need all the bells and whiste and can start with something simple and add stuff as needed - the default implementation already implements much more). Hopefully I'll perhaps end up by having my own blog/programming site and starting with a custom implementation with really the minial amount of work you need to get started with ASP.NET Identity would be likely one thing I would find useful).

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 6, 2019 1:20 PM
  • User-1764593085 posted

    Hi sakuradata,

    It seems  that the tutorial is for asp.net MVC, do you use asp.net or asp.net core MVC?

    In asp.net core, you could custom an action filter to validate session before the action executes.

    1.Create a ValidateUserActionFilter:

    public class ValidateUserActionFilter : ActionFilterAttribute
        {
            public override async void OnActionExecuting(ActionExecutingContext context)
            {
                //replace below code to get your session data
                var name = context.HttpContext.Session.GetString("UserName");
                if(name == null)
                {
                    context.Result = new RedirectResult("/Identity/Account/Login");
                    await context.Result.ExecuteResultAsync(context);
                }
                base.OnActionExecuting(context);
            }
    
        }

    2.Use it as Attribute:

    [ValidateUserActionFilter]
    public ActionResult UserDashBoard()  
        {  
               return View();  
        } 

    If you use asp.net instead of asp.net core ,refer to 

    asp.net MVC custom action filters

    Redirect From Action Filter Attribute

    Best Regards,

    Xing

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, June 7, 2019 2:30 AM