基本身份验证不工作在IE或Chrome,但工作在Firefox

Basic authentication not working in IE or Chrome but work on Firefox

本文关键字:工作 Chrome Firefox IE 身份验证      更新时间:2023-09-26

验证代码如下:

public class BasicAuthenticationMessageHandler : DelegatingHandler
    {
        private const string BasicAuthResponseHeader = "WWW-Authenticate";
        private const string BasicAuthResponseHeaderValue = "Basic";
        public IProvidePrincipal PrincipalProvider { get; set; }
        protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            AuthenticationHeaderValue authValue = request.Headers.Authorization;
            if (authValue != null && !String.IsNullOrWhiteSpace(authValue.Parameter))
            {
                Credentials parsedCredentials = ParseAuthorizationHeader(authValue.Parameter);
                if (parsedCredentials != null)
                {
                    Thread.CurrentPrincipal = PrincipalProvider
                        .CreatePrincipal(parsedCredentials.Username, parsedCredentials.Password);
                }
            }
            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 Credentials 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 Credentials()
            {
                Username = credentials[0],
                Password = credentials[1],
            };
        }
}

我使用Web API作为后端,Angularjs作为前端。当我想调用一个需要经过身份验证的用户的操作时,在firefox中我可以这样做,但在IE和chrome中我不能这样做。原因是什么?我认为这与MediaTypeFormatter有关。这是真的吗?

尝试添加一个领域到您的WWW-Authenticate头字段(如https://www.rfc-editor.org/rfc/rfc1945#section-11)。如果没有这个,IE似乎拒绝记住身份验证,尽管我不能说我在Chrome中遇到过这个问题。

这将导致类的顶部看起来像这样…

public class BasicAuthenticationMessageHandler : DelegatingHandler
{
    private const string BasicAuthResponseHeader = "WWW-Authenticate";
    private const string BasicAuthResponseHeaderValue = "Basic realm='"MyRealm'"";
    //...etc
}