您的位置:首页 > 编程语言 > ASP

ASP.NET Web API(三):安全验证之使用摘要认证(digest authentication)

2016-06-20 16:23 627 查看
在前一篇文章中,主要讨论了使用HTTP基本认证的方法,因为HTTP基本认证的方式决定了它在安全性方面存在很大的问题,所以接下来看看另一种验证的方式:digest authentication,即摘要认证。

摘要认证原理

在基本认证的方式中,主要的安全问题来自于用户信息的明文传输,而在摘要认证中,主要通过一些手段避免了此问题,大大增加了安全性。

下图为摘要验证的验证原理流程图。

namespace DigestAuthentication
{
public class AuthenticationHandler : DelegatingHandler
{
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
try
{
var headers = request.Headers;
if (headers.Authorization != null)
{
Header header = new Header(request.Headers.Authorization.Parameter,
request.Method.Method);

if (Nonce.IsValid(header.Nonce, header.NounceCounter))
{
// Just assuming password is same as username for the purpose of illustration
string password = header.UserName;

string ha1 = String.Format("{0}:{1}:{2}", header.UserName, header.Realm,
password).ToMD5Hash();

string ha2 = String.Format("{0}:{1}", header.Method, header.Uri).ToMD5Hash();

string computedResponse = String
.Format("{0}:{1}:{2}:{3}:{4}:{5}",
ha1, header.Nonce, header.NounceCounter,
header.Cnonce, "auth", ha2).ToMD5Hash();

if (String.CompareOrdinal(header.Response, computedResponse) == 0)
{
// digest computed matches the value sent by client in the response field.
// Looks like an authentic client! Create a principal.
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, header.UserName),
new Claim(ClaimTypes.AuthenticationMethod, AuthenticationMethods.Password)
};

var principal = new ClaimsPrincipal(new[] { new ClaimsIdentity(claims, "Digest") });

Thread.CurrentPrincipal = principal;

if (HttpContext.Current != null)
HttpContext.Current.User = principal;
}
}
}

var response = await base.SendAsync(request, cancellationToken);

if (response.StatusCode == HttpStatusCode.Unauthorized)
{
response.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue("Digest",
Header.UnauthorizedResponseHeader.ToString()));
}

return response;
}
catch (Exception)
{
var response = request.CreateResponse(HttpStatusCode.Unauthorized);
response.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue("Digest",
Header.UnauthorizedResponseHeader.ToString()));

return response;
}
}
}

}

摘要验证实现的核心方法


View Code
实现完成后,使用摘要验证只需要在对应的方法加上[Authorize]属性标签即可。



摘要验证的优缺点

摘要验证很好地解决了使用基本验证所担心的安全性问题。

但是永远没有绝对的安全,当用户使用字典进行穷举破解时,还是会存在一些被破解的隐患。

源码下载

源代码下载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: