我的WebAPI 2應用程序具有用於檢查訪問令牌的自定義授權篩選器。如果令牌存在,並且API具有該屬性,那麼我檢查是否存在映射到該令牌的用戶。由於API的性質,大多數方法在特定用戶的上下文中運行(即,「POST api/profile」來更新用戶的簡檔)。爲了做到這一點,我需要獲取來自訪問令牌的目標用戶信息。將主體/用戶上下文設置爲用戶對象
[當前實現,恰好型AuthorizeAttribute的屬性中]
if(myDBContext.MyUsers.Count(x => x.TheAccessToken == clientProvidedToken)){
IPrincipal principal = new GenericPrincipal(new GenericIdentity(myAccessToken), new string[] { "myRole" });
Thread.CurrentPrincipal = principal;
HttpContext.Current.User = principal;
return true;
}
這工作得很好,我能夠再使用訪問令牌做的方法的第二查找。 但是由於我已經在auth時間做了一個查詢,我不想浪費另一個數據庫調用。
[我想要做什麼(但顯然是行不通的)
MyUser user = myDBContext.MyUsers.FirstOrDefault(x => x.TheAccessToken == clientProvidedToken);
if(user != null){
// Set *SOME* property to the User object, such that it can be
// access in the body of my controller method
// (e.g. /api/profile uses this object to load data)
HttpContext.Current.User = user;
return true;
}
不知道爲什麼我沒有想到擴展GenericPrincipal - 它很好地工作!謝謝! – ShaneC