2015-01-14 72 views
2

我寫了一堆寧靜的ASP.Net Web API,我想驗證一些API。我已經用摘要式身份驗證實現從here帶有摘要式身份驗證的ASP.Net Web API

而且我剛纔提到的演示代碼here

我理解了代碼一點,但我不知道在哪裏以及如何連接現有數據庫從獲取數據客戶表。如果有人有關於如何做到這一點的信息,請分享。

以下是驗證一些方法:

DigestAuthorizationFilterAttributeBase.cs

protected override string GetAuthenticatedUser(HttpActionContext actionContext) 
    { 
     var auth = actionContext.Request.Headers.Authorization; 
     if (auth == null || auth.Scheme != Scheme) 
      return null; 

     var header = DigestHeader.Create(
      actionContext.Request.Headers.Authorization.Parameter, 
      actionContext.Request.Method.Method); 

     if (!DigestNonce.IsValid(header.Nonce, header.NounceCounter)) 
     { 
      return null; 
     } 
       var password = GetPassword(header.UserName); 

      var hash1 = String.Format(
      "{0}:{1}:{2}", 
      header.UserName, 
      header.Realm, 
      password).ToMd5Hash(); 

      var hash2 = String.Format(
       "{0}:{1}", 
       header.Method, 
       header.Uri).ToMd5Hash(); 

      var computedResponse = String.Format(
       "{0}:{1}:{2}:{3}:{4}:{5}", 
       hash1, 
       header.Nonce, 
       header.NounceCounter, 
       header.Cnonce, 
       "auth", 
       hash2).ToMd5Hash(); 

      return header.Response.Equals(computedResponse, StringComparison.Ordinal) 
       ? header.UserName 
       : null; 

    } 

DigestAuthorizationFilterAttribute.cs

public DigestAuthorizationFilterAttribute(bool issueChallenge = true) : base(issueChallenge) 
    { 

    } 

    protected override bool IsUserAuthorized(string userName) 
    { 
     return true; 
    } 

    protected override string GetPassword(string userName) 
    { 
     return userName; 
    } 

回答

1

一個例子是在下面的方法:

protected override bool IsUserAuthorized(string userName) 
{ 
    return true; 
} 

你可以做大致相似的東西:

protected override bool IsUserAuthorized(string userName) 
{ 
    var user = db.Users.Where(u => u.username = userName); 
    if(user.Any()) 
    { 
     return true; 
    } 
    else 
    { 
     return false; 
    } 
} 

你還需要檢查密碼是否有效。但你明白了。

希望這有助於。