1

我有以下两个动作,它们不断互相调用并进入无限循环。我究竟做错了什么?

Public Overrides Sub OnAuthorization(filterContext As System.Web.Mvc.AuthorizationContext)
        'This calls the AuthorzeCore function and also makes sure that the browser does not cache this function
        MyBase.OnAuthorization(filterContext)
        If Not IsNothing(filterContext.Result) Then
            Return
        End If
        'Gets the calling Controller
        Dim controllerName As String = filterContext.Controller.GetType().Name
        'Gets the calling action
        Dim actionName As String = filterContext.ActionDescriptor.ActionName

        'Checks whether the logged in user has access to the action of the controller
        Dim canAccess As test.Security.Permissions.PermissionTypes
        canAccess = test.ApplicationSecurity.GetSecurityObject().GetAccess(controllerName & "." & actionName)
        If canAccess = Security.Permissions.PermissionTypes.DISABLE Then
            'User has access to the application but not to the action they are trying to access, so throw a Unauthorised exception
            filterContext.HttpContext.Response.StatusCode = 403
            HandleUnauthorizedRequest(filterContext)
        End If

    End Sub

    Protected Overrides Sub HandleUnauthorizedRequest(filterContext As System.Web.Mvc.AuthorizationContext)
        ''To make sure that we throw a not authorised error rather not authenticated message
        'If filterContext.HttpContext.Request.IsAuthenticated Then
        '    'filterContext.Result = New HttpStatusCodeResult(CType(System.Net.HttpStatusCode.Forbidden, Int32))
        '    filterContext.Result = New RedirectToRouteResult(
        'Else
        '    MyBase.HandleUnauthorizedRequest(filterContext)
        'End If
        If (filterContext.HttpContext.Request.IsAjaxRequest()) Then
            Dim urlHelper As UrlHelper = New UrlHelper(filterContext.RequestContext)
            filterContext.Result = New JsonResult With {.Data = New With {.Error = "NotAuthorized", .URL = urlHelper.Action("UnAuthorized", "Error")}, _
                                                        .JsonRequestBehavior = JsonRequestBehavior.AllowGet}
        ElseIf filterContext.HttpContext.Response.StatusCode = 403 Then
            filterContext.Result = New ViewResult With {.ViewName = "UnAuthorized"}
        Else
            filterContext.Result = New ViewResult With {.ViewName = "UnAuthenticated"}

        End If
    End Sub
4

1 回答 1

2

你不应该HandleUnauthorizedRequest从内部调用OnAuthorization,当请求不能被授权时,这个方法会自动调用。

文档

在以下情况下拒绝授权:

• 该请求未与任何用户关联。

• 用户未通过身份验证。

• 用户已通过身份验证,但不在授权的用户组中(如果已定义),或者如果用户不在任何授权角色中(如果已定义)。

如果授权被拒绝,则此方法将调用 HandleUnauthorizedRequest(HttpActionContext) 来处理未经授权的请求。

于 2013-05-01T07:56:58.427 回答