ASP.Net MVC: IAuthorizationFilter / Attribute prefers security check for login?

Is IAuthorizationFilter combined with an attribute the preferred way to check if a user is logged in before the controller completes its course?

Since I'm new to MVC, I was trying to figure out how to handle situations executed in WebForms. The one I came across yesterday checks to see if the user can view the page or not, depending on whether it is logged in or not. When I accepted the project and "transformed" it into an MVC project, I was a little upset about how to solve this situation.

In the WebForms version, I used the base page to check if the user was logged in:

if (State.CurrentUser == null)
{
  State.ReturnPage = SiteMethods.GetCurrentUrl();
  Response.Redirect(DEFAULT_LOGIN_REDIRECT);
}

I found the following:

[AttributeUsage(AttributeTargets.Method)]
public sealed class RequiresAuthenticationAttribute : ActionFilterAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext context)
    {
        if (State.CurrentUser ==  null)
        {
            context.Result = 
              new RedirectToRouteResult
              (
                "Login", 
                new RouteValueDictionary
                (
                  new 
                  { 
                    controller = "Login", 
                    action = "Error", 
                    redirect = SiteMethods.GetCurrentUrl()
                  }
                )
              ); 
        }
    }
} 

, . , / ?

+3
2

. MVC AuthorizeAttribute, , , , . . , - .

+2

FilterAttributes - .

+1

Source: https://habr.com/ru/post/1710483/


All Articles