我创建了自己的Authorize属性,名为Authorize ...
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
我已经这样做了所以我可以在属性上使用roles参数,就像这样......
<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?
答案 0 :(得分: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"))
{
}
}