基本身份验证不工作在IE或Chrome,但工作在Firefox
Basic authentication not working in IE or Chrome but work on Firefox
验证代码如下:
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
}
相关文章:
- JS可以在Chrome中工作,但不能在Firefox中工作
- jQuery Datepicker可以在Safari中工作,但不能在FF或Chrome中工作
- Javascript的某些部分在Chrome中不起作用,但在其他浏览器中可以完美工作
- javascript window.open将无法在Chrome控制台上工作
- 如何编写在Chrome和IE中正常工作的JavaScript
- 只有当Javascript控制台在chrome上打开时,Javascript才能工作
- Chrome地理定位在更新后停止工作
- 地理定位无法在chrome中工作
- Json到CSV下载,可以在chrome中工作,但不能在IE浏览器中工作
- prettyPhoto无法在Chrome和IE9中工作
- window.location.htm无法在chrome扩展中工作
- jQuery$.post可以在chrome、safari中工作,但不能在FF中工作(声明成功回调函数未定义)
- Chrome没有加载最新版本的web工作程序脚本(运行缓存版本)
- HTML5视频无法在chrome上工作,在服务器上托管后的IE,mov文件中的视频(quicktime格式)
- 异步加载的SVG过滤器feColorMatrix在Chrome中工作,而不是在Safari或Firefox中
- JQuery 灯箱不工作.Chrome 在显示控制台中报告错误
- 如何使工作 Chrome 扩展程序的未捕获异常处理程序(由于 CORS 保护而不起作用)
- JavaScript表单脚本工作Chrome,但没有其他地方
- 锚标记下载属性不工作:Chrome 35.0.1916.114中的错误
- JQuery&子选择器A>B: 不工作?[Chrome 24,JQmobile]