如何在ASP.NET MVC 6中重定向未经授权的用户

5

我希望知道如何重定向用户。我有一个控制器Index(),我只想让拥有“学生”角色的用户进入其中!所以我使用

[Authorize(Roles="Student")]

我想知道如何将没有此角色的用户重定向到主页。

请查看以下吹箭的答案:https://dev59.com/CVwZ5IYBdhLWcg3wbv7r - rism
3个回答

8

MVC5(以及更早版本):

您可以通过更改web.config上的loginUrl属性来实现此操作。将其更改为所需的路由:

<authentication mode="Forms">
  <forms loginUrl="~/Home/Index" timeout="2880" />
</authentication>

MVC6:

MVC6中你可以尝试这样做(在Startup.cs中):

public void ConfigureServices(IServiceCollection services)
{       
    services.Configure<CookieAuthenticationOptions>(options =>
    {
        options.LoginPath = new PathString("/Home/Index");
    });
}

在MVC 6中,web.config文件不存在! - Clowning
我认为这两个命名空间都来自于 Microsoft.Owin - fabriciorissetto
好的,谢谢。我的Visual Studio有一些错误...你知道修改错误路径的属性吗?目前如果我的用户没有访问ASP,我会将用户重定向到“Account/AccessDenied”! - Clowning
哦,谢谢你FabricIO :p!但我的问题还没有解决!我想我必须重写或创建一个新的[Authorize]标记!你有在MVC 6中实现这个的想法吗? :) - Clowning
您无需创建新的 [Authorize] 属性。 - fabriciorissetto
显示剩余2条评论

1

有一种流传的方法适用于MVC5。 我认为它也适用于MVC6。
在您的控制器中,创建一个自定义身份验证方法,如下所示。

    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");
        }
    }
}

然后将您的数据注释更改为:
[YourCustomAuthorize(Roles = "Admin")]
public class UserController : Controller
{
     // Omitted for brevity
}

-6

你尝试使用会话了吗?

我猜你有一个登录页面,然后在登录后立即分类会话

然后简单的if条件就可以了。

<%If Session("userRole")="Student" Then%>
  This is the text version of the page
<%Else%>
  Response.Redirect("notavailablepage.html")
<%End If%>

3
永远不要将Session用于安全目的。它不安全,规则与身份验证和授权不同。另外,它也不可靠,因为每当应用程序池重置时,会话就会被重置。 - Erik Funkenbusch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接