2014-02-13 8 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); 
    } 

Am I Missi Что-то в коде и это правильный подход для аутентификации веб-api? Спасибо

ответ

0

Убедитесь, что учетные данные включены в заголовок и разделены ":". Положите точку останова на

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

, чтобы узнать, что представляет собой значение заголовка аутентификации.

Надеюсь, что это поможет

+0

Благодарим за отзыв. Мне удается решить проблему. Всякий раз, когда я пытаюсь войти в систему, я получаю следующую ошибку: ссылка на объект не установлена ​​в экземпляр объекта. В следующей строке кода --- api_login user = Repository.Validate2 (имя пользователя, пароль); Спасибо за помощь. – user3070072

+0

Это означает, что ваш репозиторий не был введен. Убедитесь, что значение установлено до того, как вы получите доступ к свойству –

+0

Привет, Спасибо вам за помощь. Я пишу, чтобы обратиться за помощью, как можно отлаживать класс basicAUthHandler выше. Я придерживался подхода вашего ответа, но когда я отлаживаю код, он не может найти ошибку в коде. Я использую инжектор зависимостей (Ninject), может ли это быть причиной ошибки. Спасибо за помощь и время. – user3070072

Смежные вопросы