I want to know how to redirect users. I have a Controller Index() and I want only users with the role “Student” can enter there! So I use
[Authorize(Roles="Student")]
I wonder how can I redirect users who do not have this role to the homepage
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
MVC5 (and older):
You can do this by changing the loginUrl attribute on your web.config. Change it to the desired route:
<authentication mode="Forms"> <forms loginUrl="~/Home/Index" timeout="2880" /> </authentication>
MVC6:
In MVC6 you can try this (inside the Startup.cs):
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookieAuthenticationOptions>(options =>
{
options.LoginPath = new PathString("/Home/Index");
});
}
Method 2
There is a method floating around that works for MVC5. I assume it would work for MVC6 as well.
Within your Controller, create a Custom Auth method like so.
public class YourCustomAuthorize : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
// If they are authorized, handle accordingly
if (this.AuthorizeCore(filterContext.HttpContext))
{
base.OnAuthorization(filterContext);
}
else
{
// Otherwise redirect to your specific authorized area
filterContext.Result = new RedirectResult("~/YourController/Unauthorized");
}
}
}
Then change your data annotations to
[YourCustomAuthorize(Roles = "Admin")]
public class UserController : Controller
{
// Omitted for brevity
}
Method 3
Did you try to use session for this?
I’m guessing you have login page then after login classify the session ASAP
then simple If condition will do.
<%If Session("userRole")="Student" Then%>
This is the text version of the page
<%Else%>
Response.Redirect("notavailablepage.html")
<%End If%>
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0