gpt4 book ai didi

asp.net-mvc - 如何在 ASP.NET MVC 上进行授权重定向

转载 作者:行者123 更新时间:2023-12-02 09:01:19 25 4
gpt4 key购买 nike

所以,我有 ASP.NET 2.0 WebForms 背景,是 ASP.NET MVC 的新手,我觉得它很棒,但是,我已经有点习惯了。

这一次,我的问题与身份验证和授权模型有关:

我曾经通过 Web.config 的授权部分限制文件夹

    <authorization>
<deny users="?"/>
<!--
<allow users="*"/>
-->
</authorization>

因此,当用户尝试访问私有(private)“页面”时,会被重定向到索引页面;我怎样才能在 MVC 上做到这一点?我曾经将用户 ID(或对象)保存在 session 数据中...现在我不知道如何或在哪里以 MVC 的方式存储它。

顺便说一句,我的数据模型有一个像这样的表:

CREATE TABLE user_perm (
user INT,
feature INT,
)

我想根据此表的内容限制对某些 Controller 的访问。我怎样才能实现它?

PS:我知道这些其他问题,但它们指的是测试版,我不确定是否适用于当前发布的版本。

提前致谢

最佳答案

您应该尝试对 Controller 操作进行属性过滤。 (有关详细信息,请参阅 this 链接。)

Controller 操作将您指向实际的“页面”,您应该保护这些页面。

我使用什么(自定义属性...):

Public Class ProjectController
Inherits System.Web.Mvc.Controller

<Models.Authentication.RequiresAuthentication()> _
Function Edit(ByVal id As Integer) As ActionResult

End Function

<Models.Authentication.RequiresRole(Role:="Admin")> _
Function Delete(ByVal id As Integer) As ActionResult

End Function
End Class

以及授权属性:

Namespace Models.Authentication
Public Class RequiresAuthenticationAttribute : Inherits ActionFilterAttribute
Public Overrides Sub OnActionExecuting(ByVal filterContext As System.Web.Mvc.ActionExecutingContext)
If Not filterContext.HttpContext.User.Identity.IsAuthenticated Then
Dim redirectOnSuccess As String = filterContext.HttpContext.Request.Url.AbsolutePath
Dim redirectUrl As String = String.Format("?ReturnUrl={0}", redirectOnSuccess)
Dim loginUrl As String = FormsAuthentication.LoginUrl + redirectUrl

filterContext.HttpContext.Response.Redirect(loginUrl, True)
End If
End Sub
End Class

Public Class RequiresRoleAttribute : Inherits ActionFilterAttribute
Private _role As String

Public Property Role() As String
Get
Return Me._role
End Get
Set(ByVal value As String)
Me._role = value
End Set
End Property

Public Overrides Sub OnActionExecuting(ByVal filterContext As System.Web.Mvc.ActionExecutingContext)
If Not String.IsNullOrEmpty(Me.Role) Then
If Not filterContext.HttpContext.User.Identity.IsAuthenticated Then
Dim redirectOnSuccess As String = filterContext.HttpContext.Request.Url.AbsolutePath
Dim redirectUrl As String = String.Format("?ReturnUrl={0}", redirectOnSuccess)
Dim loginUrl As String = FormsAuthentication.LoginUrl + redirectUrl

filterContext.HttpContext.Response.Redirect(loginUrl, True)
Else
Dim hasAccess As Boolean = filterContext.HttpContext.User.IsInRole(Me.Role)
If Not hasAccess Then
Throw New UnauthorizedAccessException("You don't have access to this page. Only " & Me.Role & " can view this page.")
End If
End If
Else
Throw New InvalidOperationException("No Role Specified")
End If

End Sub
End Class
End Namespace

关于asp.net-mvc - 如何在 ASP.NET MVC 上进行授权重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/957492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com