.NET Core中间件:如何访问请求凭据?

时间:2018-12-08 06:22:28

标签: c# .net-core middleware webrequest httpcontext

为了进行测试,我使用的凭据发送请求

WebRequest request = WebRequest.Create("url");
request.Credentials = new NetworkCredential("user", "pass");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

然后使用.NET Core的中间件在其他应用程序上捕获它们

public async Task Invoke(HttpContext context)

访问context.Request中的请求已成功,但是我仍在寻找context中的凭据在何处?

还是有其他解决方法?

1 个答案:

答案 0 :(得分:1)

您应该执行与here类似的操作。凭据在授权标头中编码。

bool isAuthenticated;
var base64Header = Request.Headers["Authorization"];
//The header is a string in the form of "Basic [base64 encoded username:password]"
if (base64Header != null)
{
    var authHeader = AuthenticationHeaderValue.Parse(base64Header);
    if (authHeader != null
        && authHeader.Scheme.Equals("basic", StringComparison.OrdinalIgnoreCase)
        && authHeader.Parameter != null)
    {
        //Decode the username:password pair
        var credentialPair = Encoding.ASCII.GetString(Convert.FromBase64string(authHeader.Parameter));

        //Split into pieces
        var credentials = credentialPair.Split(new [] {":"}, StringSplitOptions.None);
        var userName = credentials[0];
        var plainTextPassword = credentials[1];
        isAuthenticated = SomeAuthenticator.Authenticate(userName, password);
    }
}
if (isAuthenticated)
   return Foo();
else
   RedirectResult("your login view");