我正在try 编写一些简单的测试用户身份验证机制,它使用基本身份验证.如何从标题中检索凭据?

string authorizationHeader = this.HttpContext.Request.Headers["Authorization"];

我该怎么办?有好几本教程,但我不熟悉.NET和身份验证,你能在回答中一步一步地解释你在做什么和为什么吗.

推荐答案

从我的博客:

这将详细解释这一切是如何工作的:

步骤1-了解基本身份验证

每当您使用基本身份验证时,都会向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名称空间.

第2步-获取标题

授权头并不是HttpContext中唯一的一个.为了访问头部,我们需要从请求中获取它.

string authHeader = this.httpContext.Request.Headers["Authorization"];

(或者,您可以按照in pasx’s answer below的建议使用AuthenticationHeaderValue.TryParse)

如果您调试代码,您将看到该头文件的内容类似于以下内容:

基本QWXHZGRPBJVCGVUIHNLC2FTZQ==

第3步-判断标题

您已经提取了标题,现在需要做几件事:

  1. 判断标头是否不为空
  2. 判断授权/身份验证机制是否确实"基本"

就像这样:

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.");
}

现在,您必须判断是否有可以提取数据的内容.

第4步-提取凭据

删除"基本"子字符串

现在可以try 获取用户名和密码的值.首先,你需要go 掉"基本"子串.你可以这样做:

string encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();

有关详细信息,请参阅以下链接:

  1. http://msdn.microsoft.com/en-us/library/system.string.substring(v=vs.110).aspx
  2. http://msdn.microsoft.com/en-us/library/t97s7bs3(v=vs.110).aspx

解码Base64

现在我们需要从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);

现在您可以使用这些数据进行测试.祝你好运

"最终代码"(The Final Code)

最终代码可能如下所示:

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.");
}

.net相关问答推荐

.NET最小API BadRequest响应不返回正文

在平板电脑上运行我的 Angular 13 和 .Net Api 项目时,它不会向 api 输入请求

如何在 .Net Core EF 中组合多个条件表达式来过滤数据?

将字符串与容差进行比较

关于在 .NET 中干净地终止线程的问题

单线程单元 - 无法实例化 ActiveX 控件

从 switch 块中跳出 foreach 循环

Environment.TickCount 与 DateTime.Now

ICommand MVVM 实现

返回 IQueryable 或不返回 IQueryable

SubscribeOn 和 ObserveOn 有什么区别

读取方法的属性值

数据库架构更改后更新 LINQ to SQL 类的最佳方法

在 C# 中转义命令行参数

DateTime.TryParseExact() 拒绝有效格式

如何比较 C# 中的(目录)路径?

ILookup 接口与 IDictionary

覆盖 ASP.NET MVC 中的授权属性

ConcurrentDictionary TryRemove 何时返回 false

.NET 中的 java.lang.IllegalStateException?