2014-02-13 226 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