Dot-Net
是否存在與.net 的標準 Web 表單(不是 MVC)等效的授權屬性
我正在開發一個將使用 Windows 角色提供程序的項目,並且我想將功能限制在某些 AD 組中。
使用 MVC,我可以使用
AuthorizeAttribute上面的操作方法並相應地重定向。對於不使用 MVC 的標準 Web 表單應用程序(.NET 3.5),我可以做類似的事情嗎?
您可以在 web.config 中使用授權元素進行設置。
<configuration> <system.web> <authorization> <allow roles="domainname\Managers" /> <deny users="*" /> </authorization> </system.web> </configuration>基本上,域組在 使用
<authentication mode="Windows" />. 您可以在 MSDN 上閱讀有關它的更多資訊
我知道這是一篇舊文章,但我想我會在剛剛經歷的時候分享我的經驗。我不想使用 web.config。我正在尋找一種方法來為類似於 MVC 實現的 webforms 創建屬性。我發現了Deran Schilling的一篇文章,我將其用作屬性部分的基礎。
我創建了一個自定義 IPrincipal
interface IMyPrincipal : IPrincipal { string MyId { get; } string OrgCode { get; } string Email { get; } }和校長
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; } } }並創建了一個在頁面上使用的屬性
[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(); } }並創建了一些自定義異常
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) { } }現在我可以在給定頁面上應用該屬性以供使用
[AdminAuthorization] public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } }