Home > Blockchain >  How unauthorize access redirect user to login page
How unauthorize access redirect user to login page

Time:08-11

I am bit new in asp.net mvc. so i have a confusion where it is mention in project that unauthorize access redirect user to login page. before jumping to code i like to understand this and that is why i am positing this question where i am not able to post any code example rather i am looking for concept and guide line.

suppose i am developing a site with ASP.Net MVC core. i have created a empty project where i add two controller. one is Home and login controller.

Home controller's index action is not protected by Authorized attribute but Home controller's product action is protected.

when user try to access product action then user should be redirected to login page if not signed in. so tell me how to setup project in classic mvc or mvc core where i will mention that user should be redirected to login page if user is not signed in.

i will not use identity rather i will check user credentials from db using ado.net.

please guide me step wise that what i need to follow.

Thanks

CodePudding user response:

You can use type filter attributes to achieve that. For example if you have a BaseController class and it gets inherited in all your Controller classes, you can add a filter attribute there so that you can run your filtering's (for example: Redirect unauthorized user) before or after specific stages in the request processing pipeline.

[CheckAccessPublicStore]
public abstract class BaseController : Controller
{
}

If you want to only filter your Action method

[CheckAccessPublicStore]
public virtual IActionResult Product()
{
    return new EmptyResult();
}

Then

public class CheckAccessPublicStoreAttribute : TypeFilterAttribute
{

        public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.PublicStoreAllowNavigation))
               context.Result = = new RedirectToRouteResult(new RouteValueDictionary {
                  { "controller", "Customer" }, 
                  { "action", "LogIn" } 
                 });
        }
}

For more you can learn here: https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-6.0

  • Related