Home > Mobile >  Redirecting Anonymous User or wrong user type to login page within a specific controller in ASP.net
Redirecting Anonymous User or wrong user type to login page within a specific controller in ASP.net

Time:09-18

I have two sections to my site, one is the front end customer portal which serves as a storefront. The other is where merchants can edit their wares, prices and the look of their store page in the storefront.

The former can be accessed by anyone, anonymous user or customer accounts, but the latter should only be accessible by merchant accounts that are logged in. If someone attempts to use a link to access parts of the merchant site without being logged in as a merchant, they should be redirected to the merchant log in.

I have a few lines I can put at the top of every Action like this:

if (!(User.Identity.IsAuthenticated
    && User.IsInRole(VendorsController.Role)))
        return RedirectToAction("Login", "Vendors");

But adding that to the beginning of each action feels like it's bad practice. I've also seen a few posts about modifying the web.config but I think that's for an earlier version of MVC. Is there a way to create an event listener that interrupts an action call to redirect to login, if the user isn't logged in as the right user type? Or will I have to add this line of code to each action?

CodePudding user response:

I'd use AuthenticationFilter where you create custom AuthenticationFilter and then apply it to Controllers or Actions as per your need

  • Related