Reputation: 10984
I create a Admin Areas. I want that before access to Admin/Home/Index, you have to login at Admin/Account/Login. So, i set authorize for HomeController. Cause I'm using Asp.net Identity, so to be able to turn to Admin/Account/Login, i set on LoginPath = new PathString("/Admin/Account/Login") in StartUp.Auth.cs file.
But now, If i set Authorize for Controller on Client side, it'll be redirected to Admin/Account/Login
How to separate 2 way to authorize in one project.
Thanks so much for kind helping.
PS: I also try this but it's still doesn't work for me MVC4 areas and forms authentication
Upvotes: 1
Views: 2607
Reputation: 71
You can always do a check in the navigation area if the user is in a specific role and authenticated and choose to show / hide those specific areas if they are not. First you would want to put the [Authorize] decorator on any controllers necessary, then you can do this in your cshtml files to make sure only admins can see the admin areas.
@if (User.Identity.IsAuthenticated)
{
if (User.IsInRole("Admin"))
{
<li>@Html.ActionLink("Admin", "Admin", "Account")</li>
}
}
Upvotes: 1
Reputation: 36
I am not sure I totally understand what you are trying to do but I guess you want to redirect users to different Index page once logged-in? If so you have several options: Assuming your are using the Identity Model shipped in with MVC5:
1 - In your AccountController - Login Action (HttpPost)
After var result = await SignInManager.PasswordSignInAsync.... Add something like that :
2- Or you can create a customer ActionFilterAttribute like this one (simplified for demo purpose but yet working example):
public class RedirectLoginFilter:ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
// First check if authentication succeed and user authenticated:
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
bool IsAdmin = filterContext.HttpContext.User.IsInRole("Admin");
//Then check for user role(s) and assign view accordingly, don't forget the
//[Authorize(Roles = "YourRoleHere")] on your controller / action
if (IsAdmin)
{
filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary
(new
{
area = "Admin",
controller = "Home",
action = "Index"
}));
}
else
{
filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary
(new
{
area = "",
controller = "Home",
action = "Index"
}));
}
}
base.OnActionExecuted(filterContext);
}
Now in your default returnUrl Controller Action for all non-identificated users ie: Home/Index add your custom filterActionAttribute :
public class HomeController : Controller
{
[RedirectLoginFilter]
public ActionResult Index()
{
return View();
}
Bear in mind that with the last solution everytime your will try to access your Home/Index method with admin role you will be redirected to the admin Index page.
Upvotes: 1