我有两个不断相互调用并进入无限循环的动作。我做错了什么?
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
答案 0 :(得分:2)
您不应该从HandleUnauthorizedRequest
内部调用OnAuthorization
,当无法授权请求时会自动调用此方法。
来自docs:
在以下情况下,授权被拒绝:
•请求未与任何用户关联。
•未对用户进行身份验证。
•用户已通过身份验证,但未在授权的用户组中(如果已定义),或者用户未在 授权角色(如果已定义)。
如果授权被拒绝,则此方法将调用 HandleUnauthorizedRequest(HttpActionContext)来处理 未经授权的请求。