如何在ASP.NET MVC上进行授权重定向

时间:2022-10-21 04:14:14

So, I come from a ASP.NET 2.0 WebForms background and am new to ASP.NET MVC which I find it wonderful, however, i've been somewhat accostumed to it.

所以,我来自ASP.NET 2.0 WebForms背景,并且是ASP.NET MVC的新手,我发现它非常棒,但是,我已经对它有所了解。

This time, my problem has to do with Authentication and Authorization Model:

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

I used to restrict folders via Web.config's authorization section

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

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

So when a user tries to access a private "page" be redirected to index page; How can I do this on MVC? I used to save the user id (or object) in the session data... now I don't know how or where to store it, in a MVC'ish way.

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

As a side note, my data model has a table like this:

作为旁注,我的数据模型有一个这样的表:

CREATE TABLE user_perm (
    user INT,
    feature INT,
)

And I would like to restrict access to certain controllers based on the content of this table. Ho w can I achieve it?

我想基于此表的内容限制对某些控制器的访问。我能实现吗?

PS: i'm aware of these other questions, but they refer to beta version and I'm unsure if yet apply to the current released version.

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

Thanks in advance

提前致谢

3 个解决方案

#1


You should try attribute filtering on controller actions. (See this link for good information.)

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

Controller actions point you to actual 'pages', you should secure those.

控制器操作将您指向实际的“页面”,您应该保护它们。

What I use (custom attribute...):

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

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

And the authorization attribute:

和授权属性:

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

#2


use the Authorize attribute. You can place it on individual actions or on the entire controller.

使用Authorize属性。您可以将其置于单个操作或整个控制器上。

[Authorize(Roles="admin")]

More information here:

更多信息:

http://forums.asp.net/p/1428467/3192831.aspx

#3


They way we are handling it is through Attributes.

我们处理它的方式是通过属性。

    [Authorize]
    public ActionResult SomeAction() {
        return View();
    }

“[Authorize]” is equvalent to “[Authorize(Roles="user")]”. For specific roles use [Authorize(Roles="")].

“[授权]”等同于“[授权(角色=”用户“)]”。对于特定角色,请使用[Authorize(Roles =“”)]。

#1


You should try attribute filtering on controller actions. (See this link for good information.)

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

Controller actions point you to actual 'pages', you should secure those.

控制器操作将您指向实际的“页面”,您应该保护它们。

What I use (custom attribute...):

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

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

And the authorization attribute:

和授权属性:

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

#2


use the Authorize attribute. You can place it on individual actions or on the entire controller.

使用Authorize属性。您可以将其置于单个操作或整个控制器上。

[Authorize(Roles="admin")]

More information here:

更多信息:

http://forums.asp.net/p/1428467/3192831.aspx

#3


They way we are handling it is through Attributes.

我们处理它的方式是通过属性。

    [Authorize]
    public ActionResult SomeAction() {
        return View();
    }

“[Authorize]” is equvalent to “[Authorize(Roles="user")]”. For specific roles use [Authorize(Roles="")].

“[授权]”等同于“[授权(角色=”用户“)]”。对于特定角色,请使用[Authorize(Roles =“”)]。