Reputation: 179
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
Upvotes: 5
Views: 9408
Reputation: 653
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
}
Upvotes: 1
Reputation: 10063
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>
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");
});
}
Upvotes: 8
Reputation: 45
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%>
Upvotes: -6