授权401错误

时间:2014-02-13 12:46:14

标签: c# asp.net-mvc asp.net-web-api basic-authentication

我正在使用以下基本身份验证方法并输出以下错误 - “$ id”:“1”,“消息”:“此请求已拒绝授权”,当我调用 - api / values < / p>

    [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);
   }

我是否遗漏了代码中的内容,这是验证网络API的正确方法吗? 感谢

1 个答案:

答案 0 :(得分:0)

确保凭据包含在标题中,并以“:”分隔。在

处设一个断点
string[] credentials = Encoding.ASCII.GetString(Convert.FromBase64String(authHeader)).Split(new[] { ':' });

查看身份验证标头的值是什么。

希望这有帮助

相关问题