[英]Custom Attribute For Class Library Classes and Functions in C#
我正在 class 庫而不是ASP.NET 中開發第 3 方 API 連接器橋。
用戶等級
API 有 3 個用戶級別,比方說:
服務限制
每個 API 操作都可以與一個或多個用戶級別角色一起使用。 例如,假設操作和可達到的用戶級別如下;
如果 UserDoer 請求 JokerService,API 返回錯誤請求。 JokerService 僅對 UserGoer 和 UserMaker 可用。 所以,我想限制並拋出異常。
用戶令牌結構
public interface IToken
{
string AccessToken { get; set; }
string RefreshToken { get; set; }
}
public class AuthenticationToken : IToken
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
[JsonProperty("refresh_token")]
public string RefreshToken { get; set; }
}
public class UserGoerAuthenticationToken : AuthenticationToken
{
}
public class UserDoerAuthenticationToken : AuthenticationToken
{
}
public class UserMakerAuthenticationToken : AuthenticationToken
{
}
枚舉
public enum TokenType
{
Undefined = 0,
UserGoer = 1,
UserDoer = 2,
UserMaker = 3
}
自定義身份驗證屬性
public class AuthenticationFilter : Attribute
{
public TokenType[] TokenTypes { get; private set; }
public AuthenticationFilter(params TokenType[] TokenTypes)
{
this.TokenTypes = TokenTypes;
}
}
示例服務
[AuthenticationFilter(TokenType.UserGoer, TokenType.UserMaker)]
internal class JokerService : BaseService<JokerEntity>
{
public JokerService(IToken AuthenticationToken) : base(AuthenticationToken)
{
var tokenTypes =
(typeof(JokerService).GetCustomAttributes(true)[0] as AuthenticationFilter)
.TokenTypes;
bool throwExceptionFlag = true;
foreach (var item in tokenTypes)
{
// Check AuthenticationToken is UserGoer or UserMaker by StartsWith function
if (AuthenticationToken.GetType().Name.StartsWith(item.ToString()))
{
throwExceptionFlag = false;
break;
}
}
if (throwExceptionFlag)
throw new Exception("Invalid Authentication Token");
}
public JokerEntity Create(RequestModel<JokerEntity> model) => base.Create(model);
public JokerEntity Update(RequestModel<JokerEntity> model) => base.Update(model);
public JokerEntity Get(RequestModel<JokerEntity> model) => base.Get(model);
public List<JokerEntity> List(RequestModel<JokerEntity> model) => base.List(model);
}
綜上所述,JokerService 可以被 UserGoer 和 UserMaker 執行。 UserDoer 沒有此服務的權限。
正如您看到的AuthenticationFilter
屬性的用法,我在構造函數中獲取自定義屬性,因為我想知道IToken
是什么。 如果有一個不相關的“用戶身份驗證令牌”類型作為參數 (IToken) 傳遞,程序應該拋出異常。
這是我的解決方案,您認為我的問題有什么最佳實踐嗎?
謝謝您的幫助。
有趣的問題。 我對建設性批評的最初想法是,特定 class 通過屬性接受的標記是在編譯時決定的,無法更改。 但是,權限檢查發生在每個 object 的構造上。
您可以使用設置tokenTypes
變量的static
構造函數來防止這種情況。 Static 構造函數總是在實例構造函數之前運行。 這也是確保tokenTypes
永遠不會是 null(在沒有自定義屬性的情況下)的好地方。
同樣,遍歷tokenTypes
的循環可能是 function,它接受IToken
和tokenTypes
,更重要的是,可能存在於 BaseService.cs 中。 當某些未來的需求需要對其進行更改時,編寫一次該邏輯將使它更容易維護。 :)
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.