将 BasicAuthentication 添加到 ASP.NET Core 2.1 Web API 项目

Adding BasicAuthentication to an ASP.NET Core 2.1 Web API project

我有一个针对 .NET Framework 4.6.2 的 ASP.NET Core 2.1 Web API 项目,现在我需要向其添加基本身份验证。在有人问之前,我需要以 .NET Framework 4.6.2 为目标,因为我仍在使用 EntityFramework 6(我们的回购有一个 database-first 方法,我需要 EDMX 模型)。

在 Internet 上找到了几个示例,但它们都依赖于注入的 IServiceCollection object 的 AddAuthentication 方法。可能是因为我拥有 .NET Core/.NET Framework 组合,在我的情况下该方法不可用。相反,我有具有不同签名的 AddAuthenticationCore。我找不到 AddAuthenticationCode 方法的任何示例。谁能帮忙? 谢谢, 埃德

编辑: 我找到了有关此 AddAuthenticationCore 的一些信息,并在文档的帮助下,将其添加到 ConfigureServices 方法中:

     // add basic authentication
     services.AddAuthenticationCore(options =>
     {
        options.AddScheme<BasicAuthenticationHandler>("BasicAuthentication", null);
        options.DefaultAuthenticateScheme = "BasicAuthentication";
     });

我的 BasicAuthenticationHandler class 是这样装饰的:

public class BasicAuthenticationHandler : IAuthenticationHandler
{
  private HttpContext _context;

  public Task<AuthenticateResult> AuthenticateAsync()
  {
     if(_context.Request.Headers.ContainsKey("Authorization"))
     {
        return Task.FromResult(AuthenticateResult.Fail("Missing Authorization Header."));
     }

     try
     {
        var authHeader = AuthenticationHeaderValue.Parse(_context.Request.Headers["Authorization"]);
        var credentialBytes = Convert.FromBase64String(authHeader.Parameter);
        var credentials = Encoding.UTF8.GetString(credentialBytes).Split(':');
        var username = credentials[0];
        var password = credentials[1];

        if(username.Equals("My_User") && password.Equals("MyPassword"))
        {
           var claims = new[] {
              new Claim("UserId", username),
              new Claim("UserName", username),
           };
           var identity = new ClaimsIdentity(claims, "BasicAuthentication");
           var principal = new ClaimsPrincipal(identity);
           var ticket = new AuthenticationTicket(principal, "BasicAuthenticationScheme");

           return Task.FromResult(AuthenticateResult.Success(ticket));
        }
        else
        {
           return Task.FromResult(AuthenticateResult.Fail("Invalid User Name or Password"));
        }
     }
     catch
     {
        return Task.FromResult(AuthenticateResult.Fail("Invalid Authorization Header"));
     }
  }

  public Task ChallengeAsync(AuthenticationProperties properties)
  {
     throw new NotImplementedException();
  }

  public Task ForbidAsync(AuthenticationProperties properties)
  {
     throw new NotImplementedException();
  }

  public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context)
  {
     _context = context;
     return Task.FromResult<object>(null);
  }

}

我在 InitializeAsync 和 AuthenticateAsync 中都有断点,但调用了其中 none 个断点。即使 Autorization header 包含错误的密码,我的调用仍然成功。知道为什么我的基本身份验证处理程序无效吗? 这里有类似的问题,其答案表明必须在 Configure 内部调用 UseAuthentication。问题是我无权访问该方法:

尝试从 Nuget 安装 Microsoft.AspNetCore.Authentication 包。它以 .NET Standard 为目标,因此可用于 .NET Core 和 Framework。之后你应该可以调用 IServiceCollection.AddAuthentication().