15

在我的ASP.NET Web API項目中,我使用的承載令牌的授權,我已經加入到它的一些自定義聲明,就像這樣:獲取自定義聲明值

var authType = AuthConfig.OAuthOptions.AuthenticationType; 
var identity = new ClaimsIdentity(authType); 
identity.AddClaim(new Claim(ClaimTypes.Name, vm.Username)); 

// custom claim 
identity.AddClaim(new Claim("CompanyID", profile.CompanyId.ToString())); 

是有什麼方法可以在控制器中訪問這個額外的聲明值,而無需額外訪問數據庫?

回答

22

當然,你的保護控制器中執行以下操作:

ClaimsPrincipal principal = Request.GetRequestContext().Principal as ClaimsPrincipal; 
var customClaimValue = principal.Claims.Where(c => c.Type == "CompanyID").Single().Value; 
+0

我怎麼能重用這個更集中的方式?我正在使用需要的服務層,即「customClaimValue」。所有控制器操作都需要在獲取/發佈數據之前將此值發送到服務。 – 2015-03-07 15:07:43

+1

您可以創建自定義過濾器,然後按下您的操作方法 – 2015-03-08 22:54:25

+1

謝謝,不知道您可以在過濾器中獲取當前請求。還有一個非常漂亮的博客,Taiseer! – 2015-03-09 08:30:29