2014-02-19 29 views
3

我上了一個新的應用程序工作的強制執行ClaimType和正在使用ASP.NET身份,想知道是否有強制執行特定的聲明類型存在於ClaimsIdentity的方式。以下是我迄今爲止..它的工作原理,但它似乎有這個東西會應建/在,也許我只是沒有找到它。上ClaimsIdentity

public void SignIn(IUserIdentity user, string authenticationType, bool isPersistent) 
    { 
     if (user == null) 
     { 
      string msg = "UserIdentity or UserIdentity is null"; 
      _logger.Error(msg); 
      throw new NullReferenceException(msg); 
     } 
     List<Claim> claims = _claimService.GetClaims(user.UserId); 

     var identity = new ClaimsIdentity(claims, authenticationType, ClaimTypes.Name, ClaimTypes.Role); 
     if (claims.Any() && claims.Single(c => c.Type == ClaimTypes.Name).Value != null) 
     { 
      _owinContext.Authentication.SignIn(new AuthenticationProperties 
      { 
       IsPersistent = isPersistent 
      }, identity); 
     } 
     else 
     { 
      throw new SecurityException("Invalid or null Name Claim");  
     } 

    } 

回答

3

我不知道有任何內置的方式來斷言索賠存在。

編輯

你是對的。我原來的解決方案是過度設計的。我認爲你的解決方案是唯一的出路。

驗證不正確,但有兩個原因:

  • 一個例外是拋出,如果要求沒有因爲.Single發現使用
  • Claim的值不能爲空,因爲它的構造防止它

它應該是:

List<Claim> claims = _claimService.GetClaims(user.UserId); 
if (claims.Any(i => i.Type == ClaimTypes.Name) 
{ 
    var identity = new ClaimsIdentity(claims, authenticationType, ClaimTypes.Name, ClaimTypes.Role); 

或者

var claims = _claimService.GetClaims(user.UserId); 
var identity = new ClaimsIdentity(claims, authenticationType, ClaimTypes.Name, ClaimTypes.Role); 
if (identity.Name != null) 
{ 

原始

我會怎麼做是分離認證和授權。

身份驗證 - 驗證用戶

授權 - 驗證哪些用戶是經過授權的。

public class ClaimsAuthorizeAttribute : AuthorizeAttribute 
{ 
    public string[] ClaimTypes { get; set; } 

    protected override bool AuthorizeCore(HttpContextBase httpContext) 
    { 
     if (httpContext == null) { throw new ArgumentNullException("httpContext"); } 

     var principal = httpContext.User as ClaimsPrincipal; 
     return principal != null && HasAllClaimTypes(principal) && base.AuthorizeCore(httpContext); 
    } 

    private bool HasAllClaimTypes(ClaimsPrincipal principal) 
    { 
     return ClaimTypes == null || ClaimTypes.All(claimType => principal.HasClaim(claim => claim.Type == claimType)); 
    } 
} 

強制所有控制器都需要在全局過濾器像這樣聲明類型:

filters.Add(new ClaimsAuthorizeAttribute { ClaimTypes = new[]{ ClaimTypes.Name } }); 

當一個聲明類型不存在,用戶被重定向到登錄頁面。 (您可能需要改變,雖然這種行爲)

看到這篇文章太http://leastprivilege.com/2012/10/26/using-claims-based-authorization-in-mvc-and-web-api/

+0

高興知道我不是完全堅果和缺少的東西。我完全,幾乎逐字地回答你的答案......太有趣了。 – DfwForSale

+0

這不工作的偉大,但我並不需要檢查每個請求,是的,這是一個全球性的屬性,似乎有點矯枉過正。我只需要聲明我有一個名稱標識符。 – DfwForSale

+0

嗯... OK。我會盡量在明天提出一個更好的解決方案。我需要「冬眠」瞬間,因爲它是過去的午夜在這裏。 – LostInComputer

相關問題