簡體   English   中英

如何從標頭中檢索基本身份驗證憑據?

[英]How can I retrieve Basic Authentication credentials from the header?

我正在嘗試編寫一些使用基本身份驗證的簡單測試用戶身份驗證機制。 如何從標題中檢索憑據?

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

我從這里去哪里? 有幾個教程,但我是 .NET 和身份驗證的新手,您能否在答案中逐步解釋您正在做什么以及為什么這樣做。

來自我的博客:

這將詳細解釋這一切是如何工作的:

第 1 步 - 了解基本身份驗證

每當您使用基本身份驗證時,都會在 HTTP 請求中添加一個標頭,它看起來類似於:

授權:基本 QWxhZGRpbjpvcGVuIHNlc2FtZQ==

來源: http : //en.wikipedia.org/wiki/Basic_access_authentication

“QWxhZGRpbjpvcGVuIHNlc2FtZQ==”只是以Base64( http://en.wikipedia.org/wiki/Base64 )編碼的“用戶名:密碼”。 為了訪問 .NET (C#) 中的標頭和其他 HTTP 屬性,您需要訪問當前的 Http 上下文:

HttpContext httpContext = HttpContext.Current;

您可以在 System.Web 命名空間中找到它。

第 2 步 - 獲取標題

授權標頭並不是 HttpContext 中唯一的標頭。 為了訪問標頭,我們需要從請求中獲取它。

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

(或者,您可以按照下面 pasx 的回答中的建議使用AuthenticationHeaderValue.TryParse

如果您調試代碼,您將看到該標頭的內容類似於以下內容:

基本 QWxhZGRpbjpvcGVuIHNlc2FtZQ==

第 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 步 - 提取憑據

刪除“基本”子字符串

您現在可以嘗試獲取用戶名和密碼的值。 首先,您需要擺脫“基本”子字符串。 你可以這樣做:

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);

現在您可以使用這些數據進行測試。 祝你好運!

最終代碼

最終代碼可能如下所示:

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

只是添加到主要答案中,擺脫“基本”子字符串的最佳方法是使用AuthenticationHeaderValue Class

var header = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
var credentials = header.Parameter;

如果標頭的內容無效,它將拋出 FormatException,例如:“基本”部分不存在。

或者,如果您不想出現異常,請使用AuthenticationHeaderValue.TryParse

來自@DawidO 的精彩回答。

如果您只是想提取基本的身份驗證憑證並依賴 .NET 魔法,因為您有 HttpContext,這也將起作用:

  public static void StartListener() {
    using (var hl = new HttpListener()) {
      hl.Prefixes.Add("http://+:8008/");
      hl.AuthenticationSchemes = AuthenticationSchemes.Basic;
      hl.Start();
      Console.WriteLine("Listening...");
      while (true) {
        var hlc = hl.GetContext();

        var hlbi = (HttpListenerBasicIdentity)hlc.User.Identity;
        Console.WriteLine(hlbi.Name);
        Console.WriteLine(hlbi.Password);

        //TODO: validater user
        //TODO: take action
      }
    }
  }

請記住,使用字符串可能不太安全。 它們將保留在內存中,直到它們被 GC 選中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM