2017-08-10 98 views
2

我已經使用WebAPI 2應用程序實現了Oauth,並且有幾個應用程序訪問該API。是否有可能通過WebAPI 2中的authToken(RequestContext)訪問clientId

var currentUser = RequestContext.Principal; 

登錄時,該clientId設置如下:

context.OwinContext.Set<AppClient>("oauth:client", client); 

有沒有通過身份驗證後,發出請求,而在整個身份驗證令牌發送後,我可以按如下方式訪問用戶訪問該客戶端ID的方式?我想限制某些操作/控制器到某些客戶端。有沒有辦法做到這一點?

我試圖讓客戶如下:

var client = Request.GetOwinContext().Get<string>("oauth:client"); 

,但是這是行不通的。

回答

2

登錄時,你可以在GrantResourceOwnerCredentials

identity.AddClaim(new Claim("oauth:client", client)); 

設置要求的身份這樣,它可一旦用戶主體的身份進行設置。

您可以創建一個擴展方法一旦你的用戶主要可以從權利要求提取客戶ID,以方便提取它

public static class GenericIdentityExtensions { 
    const string ClientIdentifier = "oauth:client"; 

    /// <summary> 
    /// Set the client id claim 
    /// </summary> 
    /// <param name="identity"></param> 
    /// <returns></returns> 
    public static bool SetClientId(this IIdentity identity, string clientId) { 
     if (identity != null) { 
      var claimsIdentity = identity as ClaimsIdentity; 
      if (claimsIdentity != null) { 
       claimsIdentity.AddClaim(new Claim(ClientIdentifier, clientId)); 
       return true; 
      } 
     } 
     return false; 
    }   

    /// <summary> 
    /// Return the client id claim 
    /// </summary> 
    /// <param name="identity"></param> 
    /// <returns></returns> 
    public static string GetClientId(this IIdentity identity) { 
     if (identity != null) { 
      var claimsIdentity = identity as ClaimsIdentity; 
      if (claimsIdentity != null) { 
       return claimsIdentity.FindFirstOrEmpty(ClientIdentifier); 
      } 
     } 
     return string.Empty; 
    } 
    /// <summary> 
    /// Retrieves the first claim that is matched by the specified type if it exists, String.Empty otherwise. 
    /// </summary> 
    public static string FindFirstOrEmpty(this ClaimsIdentity identity, string claimType) { 
     var claim = identity.FindFirst(claimType); 
     return claim == null ? string.Empty : claim.Value; 
    } 
} 

所以現在。

var currentUser = RequestContext.Principal; 
var client = currentUser.Identity.GetClientId(); 
相關問題