我正在try 编写一些简单的测试用户身份验证机制,它使用基本身份验证.如何从标题中检索凭据?
string authorizationHeader = this.HttpContext.Request.Headers["Authorization"];
我该怎么办?有好几本教程,但我不熟悉.NET和身份验证,你能在回答中一步一步地解释你在做什么和为什么吗.
我正在try 编写一些简单的测试用户身份验证机制,它使用基本身份验证.如何从标题中检索凭据?
string authorizationHeader = this.HttpContext.Request.Headers["Authorization"];
我该怎么办?有好几本教程,但我不熟悉.NET和身份验证,你能在回答中一步一步地解释你在做什么和为什么吗.
从我的博客:
这将详细解释这一切是如何工作的:
每当您使用基本身份验证时,都会向HTTP请求添加一个标头,如下所示:
授权:基本QWXHZGRPBJPCGVUIHNLC2FTZQ==
来源:http://en.wikipedia.org/wiki/Basic_access_authentication
"QWxhZGRpbjpvcGVuIHNlc2FtZQ=="只是用base64(http://en.wikipedia.org/wiki/Base64)编码的"username:password".要访问.NET(C#)中的标头和其他HTTP属性,您需要有权访问当前的http上下文:
HttpContext httpContext = HttpContext.Current;
这一点你可以在系统中找到.Web名称空间.
授权头并不是HttpContext中唯一的一个.为了访问头部,我们需要从请求中获取它.
string authHeader = this.httpContext.Request.Headers["Authorization"];
(或者,您可以按照in pasx’s answer below的建议使用AuthenticationHeaderValue.TryParse)
如果您调试代码,您将看到该头文件的内容类似于以下内容:
基本QWXHZGRPBJVCGVUIHNLC2FTZQ==
您已经提取了标题,现在需要做几件事:
就像这样:
if (authHeader != null && authHeader.StartsWith("Basic")) {
//Extract credentials
} else {
//Handle what happens if that isn't the case
throw new Exception("The authorization header is either empty or isn't Basic.");
}
现在,您必须判断是否有可以提取数据的内容.
现在可以try 获取用户名和密码的值.首先,你需要go 掉"基本"子串.你可以这样做:
string encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
有关详细信息,请参阅以下链接:
现在我们需要从Base64解码回字符串:
//the coding should be iso or you could use ASCII and UTF-8 decoder
Encoding encoding = Encoding.GetEncoding("iso-8859-1");
string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));
现在用户名和密码将采用以下格式:
username:password
为了获取用户名和密码,我们只需获取":"的索引即可
int seperatorIndex = usernamePassword.IndexOf(':');
username = usernamePassword.Substring(0, seperatorIndex);
password = usernamePassword.Substring(seperatorIndex + 1);
现在您可以使用这些数据进行测试.祝你好运
最终代码可能如下所示:
HttpContext httpContext = HttpContext.Current;
string authHeader = this.httpContext.Request.Headers["Authorization"];
if (authHeader != null && authHeader.StartsWith("Basic")) {
string encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
Encoding encoding = Encoding.GetEncoding("iso-8859-1");
string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));
int seperatorIndex = usernamePassword.IndexOf(':');
var username = usernamePassword.Substring(0, seperatorIndex);
var password = usernamePassword.Substring(seperatorIndex + 1);
} else {
//Handle what happens if that isn't the case
throw new Exception("The authorization header is either empty or isn't Basic.");
}