Ich weiß, dies ist ein alter Beitrag, aber dachte, ich würde meine Erfahrungen teilen, wie ich gerade durch diese ging. Ich wollte nicht web.config verwenden. Ich suchte nach einer Möglichkeit, ein Attribut für Webforms zu erstellen, das der MVC-Implementierung ähnelt. Ich habe einen Beitrag von Deran Schilling gefunden, den ich als Basis für den Attributteil verwendet habe.
habe ich eine benutzerdefinierte IPrincipal
interface IMyPrincipal : IPrincipal
{
string MyId { get; }
string OrgCode { get; }
string Email { get; }
}
und Haupt
public class MyPrincipal : IMyPrincipal
{
IIdentity identity;
private List<string> roles;
private string email;
private string myId;
private string orgCode;
public MyPrincipal(IIdentity identity, List<string> roles, string myId, string orgCode, string email)
{
this.identity = identity;
this.roles = roles;
this.myId = myId;
this.orgCode = orgCode;
this.email = email;
}
public IIdentity Identity
{
get { return identity; }
}
public bool IsInRole(string role)
{
return roles.Contains(role);
}
public string Email
{
get { return email; }
}
public string MyId
{
get { return myId; }
}
public string OrgCode
{
get { return orgCode; }
}
}
und erstellt ein Attribut für den Einsatz auf der Seite
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class AdminAuthorizationAttribute : Attribute
{
public AdminAuthorizationAttribute()
{
var user = (MyPrincipal)HttpContext.Current.User;
if (user.IsInRole("MyAdmin"))
return;
throw new AccessDeniedException();
}
}
und erstellt einige benutzerdefinierte Ausnahmen
public class AccessDeniedException : BaseHttpException
{
public AccessDeniedException() : base((int)HttpStatusCode.Unauthorized, "User not authorized.") { }
}
public class BaseHttpException : HttpException
{
public BaseHttpException(int httpCode, string message) : base(httpCode, message) { }
}
und jetzt kann ich das Attribut für die Verwendung auf einer bestimmten Seite
[AdminAuthorization]
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
Recht bekam ich das beantragen. Aber gibt es eine Möglichkeit, den Zugriff auf eine bestimmte Methodenebene zu beschränken, ähnlich wie bei MVC? –
@Blair Jones, Sie müssen eine Überprüfung wie 'if (User.IsInRole (" Somerole "))' innerhalb der Methode, fürchte ich. –
ok danke ... das ist, wovor ich Angst hatte :( –