1

我创建了自己的 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?

4

1 回答 1

0

我对此没有适当的解决方案。在有人发布正确的解决方案之前,只是一个解决方法可能会有所帮助。

我将 [Authorize] 属性用于操作,但每当我处于局部视图中时,我都会手动执行“OnAuthorization”。

public class Authorize : AuthorizeAttribute
{
 public override void OnAuthorization(AuthorizationContext filterContext)
 {
   ....
 }

 public static void ManualOnAuthorization(HttpContext context)
 {
    if (context.User.Identity.IsAuthenticated && context.User.Identity.AuthenticationType == "Forms")
    {
        FormsIdentity fIdent = (FormsIdentity)context.User.Identity;
        var user = new CustomUser(fIdent.Ticket.UserData);
        var ci = new CustomIdentity(user);
        var p = new CustomPrincipal(ci);
        HttpContext.Current.User = p;
        Thread.CurrentPrincipal = p;
    }
 }
}

我已将它放在 Authorize 类中,并在部分视图中如下使用它。

@if(User.Identity.IsAuthenticated)
    {
        Authorize.ManualOnAuthorization(HttpContext.Current); 
        if (User.IsInRole("Admin"))
        {
        }
    }
于 2013-01-02T15:51:17.080 回答