2012-05-03 104 views
4

我一直在尋找授權與AspNetWebApi和信息是有點稀疏的主題。WebApi授權過濾器與JSON有效載荷中的令牌

我有以下選項:

  1. 通API令牌上的查詢字符串
  2. 通API令牌頭
  3. 通API令牌使用基本身份驗證
  4. 通API令牌到請求json中的有效載荷。

這通常是推薦的方法?

我也想知道點4),我將如何去檢查AuthorizationFilterAttribute的OnAuthorization方法中的json有效負載來檢查API令牌是否正確?

+0

你說的API令牌是什麼意思?你的意思是認證cookie? – Aliostad

+0

只需在每個請求中傳遞一個GUID即可對客戶端進行身份驗證。 – jaffa

回答

5

如果您想要一個真正安全的授權選項,類似OAuth這樣的方法就行了。這blog post提供了一個相當徹底的示例使用現在已過時的WCF Web API,但很多代碼是可挽救的。或者至少,使用HTTP基本認證,如blog post所示。正如Aliostad所指出的,如果您使用基本身份驗證路由,請確保您使用的是HTTPS,以便令牌保持安全。

如果您決定要推出自己的產品(幾乎總是比上述任一選項的安全性要低),那麼以下代碼示例說明如果您使用HTTP標頭路由,您需要爲AuthorizationHanlder提供什麼。請注意,在Web API類中處理UserPrinicipal的方式可能會發生變化,所以此代碼僅適用於第一次預覽版本。您將需要線在AuthorizationHandler這樣的:

的頭標記
GlobalConfiguration.Configuration.MessageHandlers.Add(new AuthenticationHandler()); 

代碼:

public class AuthenticationHandler : DelegatingHandler 
{ 
    protected override Task<HttpResponseMessage> SendAsync(
     HttpRequestMessage request, 
     CancellationToken cancellationToken) 
    { 
     var requestAuthTokenList = GetRequestAuthTokens(request); 
     if (ValidAuthorization(requestAuthTokenList)) 
     { 
      //TODO: implement a Prinicipal generator that works for you 
      var principalHelper = GlobalConfiguration.Configuration 
       .ServiceResolver 
        .GetService(typeof(IPrincipalHelper)) as IPrincipalHelper; 

      request.Properties[HttpPropertyKeys.UserPrincipalKey] = 
       principalHelper.GetPrinicipal(request); 

      return base.SendAsync(request, cancellationToken); 
     } 
     /* 
     ** This will make the whole API protected by the API token. 
     ** To only protect parts of the API then mark controllers/methods 
     ** with the Authorize attribute and always return this: 
     ** 
     ** return base.SendAsync(request, cancellationToken); 
     */ 
     return Task<HttpResponseMessage>.Factory.StartNew(
      () => new HttpResponseMessage(HttpStatusCode.Unauthorized) 
       { 
        Content = new StringContent("Authorization failed") 
       }); 
    } 

    private static bool ValidAuthorization(IEnumerable<string> requestAuthTokens) 
    { 
     //TODO: get your API from config or however makes sense for you 
     var apiAuthorizationToken = "good token"; 
     var authorized = requestAuthTokens.Contains(apiAuthorizationToken); 

     return authorized; 
    } 

    private static IEnumerable<string> GetRequestAuthTokens(HttpRequestMessage request) 
    { 
     IEnumerable<string> requestAuthTokens; 
     if (!request.Headers.TryGetValues("SomeHeaderApiKey", out requestAuthTokens)) 
     { 
      //Initialize list to contain a single not found token: 
      requestAuthTokens = new[] {"No API token found"}; 
     } 
     return requestAuthTokens; 
    } 
} 
+3

+1。小心只能使用HTTPS進行基本身份驗證。 – Aliostad

+0

完全正確,Aliostad!它如此根深蒂固,我忘了甚至提及它。謝謝!! –

+0

在標頭中傳遞令牌或使用基本身份驗證之間是否有任何缺點?是否將API標記放入json中並請求?另外,Principal Generator如何工作? – jaffa