我的身份验证代码如下所示:
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有关。这是真的吗?
答案 0 :(得分:0)
尝试向您的WWW-Authenticate
标头字段添加领域(根据http://tools.ietf.org/html/rfc1945#section-11)。没有这个,似乎IE拒绝记住身份验证,虽然我不能说我在Chrome中遇到了这个问题。
这会导致班级的顶部看起来像这样......
public class BasicAuthenticationMessageHandler : DelegatingHandler
{
private const string BasicAuthResponseHeader = "WWW-Authenticate";
private const string BasicAuthResponseHeaderValue = "Basic realm=\"MyRealm\"";
//...etc
}