我创建了自己的 Authorize 属性,称为 Authorise...
Imports System.Security.Principal
<AttributeUsage(AttributeTargets.Method Or AttributeTargets.[Class], Inherited:=True, AllowMultiple:=True)>
Public Class AuthoriseAttribute
Inherits AuthorizeAttribute
Public Overrides Sub OnAuthorization(filterContext As AuthorizationContext)
Dim CookieName As String = FormsAuthentication.FormsCookieName
If Not filterContext.HttpContext.User.Identity.IsAuthenticated OrElse filterContext.HttpContext.Request.Cookies Is Nothing OrElse filterContext.HttpContext.Request.Cookies(CookieName) Is Nothing Then
HandleUnauthorizedRequest(filterContext)
Return
End If
Dim AuthCookie = filterContext.HttpContext.Request.Cookies(CookieName)
Dim AuthTicket = FormsAuthentication.Decrypt(AuthCookie.Value)
Dim Roles As String() = AuthTicket.UserData.Split(","c)
Dim UserIdentity = New GenericIdentity(AuthTicket.Name)
Dim UserPrincipal = New GenericPrincipal(UserIdentity, Roles)
filterContext.HttpContext.User = UserPrincipal
MyBase.OnAuthorization(filterContext)
End Sub
End Class
我已经这样做了,所以我可以在属性上使用角色参数,就像这样......
<Authorise(Roles:="Admin")>
这在我需要授权的页面上完美运行。但是,在不需要授权(因此没有 Authorize 属性)的主页上,我想根据用户是否(a)登录和(b)他们是管理员还是管理员来显示不同的项目不是。例如...
@If HttpContext.Current.User.Identity.IsAuthenticated Then
' Display a welcome message (this works)
@If HttpContext.Current.User.IsInRole("Admin") Then
' Display a settings link (this does not work)
End If
End If
“欢迎消息”部分会触发,但“设置链接”部分不会。这是有道理的,因为这个视图没有 Authorize 属性。
如何在没有 Authorize 属性的页面上检查 IsInRole?