2014-02-13 255 views
0

我使用以下基本身份驗證方法並輸出以下錯誤 - 「$ id」:「1」,「消息」:「授權已被拒絕此請求」,當我打電話時 - api /值授權401錯誤

[Authorize] 
    public IEnumerable<string> Get() 
    { 
     return new string[] { "value1", "value2" }; 
    } 

BasicAuthMessageHandler類:

public class BasicAuthMessageHandler : DelegatingHandler 
{ 

    private const string BasicAuthResponseHeader = "WWW-Authenticate"; 
    private const string BasicAuthResponseHeaderValue = "Basic"; 

    [Inject] 
    public iUser Repository { get; set; } 

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 
    { 
     AuthenticationHeaderValue authValue = request.Headers.Authorization; 
     if (authValue != null && !String.IsNullOrWhiteSpace(authValue.Parameter)) 
     { 
      api_login parsedCredentials = ParseAuthorizationHeader(authValue.Parameter); 
      if (parsedCredentials != null) 
      { 
       IPrincipal principal; 
       if (TryGetPrincipal(parsedCredentials.username, parsedCredentials.password, out principal)) 
       { 
        Thread.CurrentPrincipal = principal; 
       } 
      } 
     } 

     return base.SendAsync(request, cancellationToken).ContinueWith(task => 
     { 
      var response = task.Result; 
      if (response.StatusCode == HttpStatusCode.Unauthorized && !response.Headers.Contains(BasicAuthResponseHeader)) 
      { 
       response.Headers.Add(BasicAuthResponseHeader, BasicAuthResponseHeaderValue); 
      } 

      return response; 
     }); 
    } 

    private api_login ParseAuthorizationHeader(string authHeader) 
    { 
     string[] credentials = Encoding.ASCII.GetString(Convert.FromBase64String(authHeader)).Split(new[] { ':' }); 
     if (credentials.Length != 2 || string.IsNullOrEmpty(credentials[0]) || string.IsNullOrEmpty(credentials[1])) return null; 

     return new api_login() 
     { 
      username = credentials[0], 
      password = credentials[1], 
     }; 
    } 

    private bool TryGetPrincipal(string userName, string password, out IPrincipal principal) 
    { 
     // this is the method that authenticates against my repository (in this case, hard coded) 
     // you can replace this with whatever logic you'd use, but proper separation would put the 
     // data access in a repository or separate layer/library. 
     api_login user = Repository.Validate2(userName, password); 

     if (user != null) 
     { 
      // once the user is verified, assign it to an IPrincipal with the identity name and applicable roles 
      //principal = new GenericPrincipal(new GenericIdentity(user.username)); 
      principal = new GenericPrincipal(new GenericIdentity(user.username), System.Web.Security.Roles.GetRolesForUser(user.role)); 
      return true; 
     } 

     principal = null; 
     return false; 
    } 
} 

用戶等級:

public api_login Validate2(string userName, string Password) 
    { 
     // Find a user that matches that username and password (this will only validate if both match) 
     return db.api_login.FirstOrDefault(u => u.username == userName && u.password == Password); 
    } 

上午我米西在代碼中的東西,這是正確的方法來驗證Web API? 謝謝

回答

0

確保憑證包含在標題中,並以「:」分隔。請在

string[] credentials = Encoding.ASCII.GetString(Convert.FromBase64String(authHeader)).Split(new[] { ':' }); 

的中斷點處查看認證標頭的值。

希望這會有所幫助

+0

謝謝你的迴應。我設法解決問題,每當我嘗試登錄時,我得到以下錯誤 - 對象引用未設置爲對象的實例。在以下代碼行--- api_login user = Repository.Validate2(userName,password);感謝您的幫助。 – user3070072

+0

這意味着您的Repository尚未注入。確保在訪問屬性之前設置了該值 –

+0

嗨,感謝您的幫助。我正在寫求助,上面怎麼能調試basicAUthHandler類。我遵循你的答案,但是當我調試代碼時,它無法在代碼中發現錯誤。我正在使用依賴注入器(Ninject),這是否可能導致錯誤。感謝您的幫助和時間。 – user3070072