简体   繁体   English

.NET CORE 2.2 身份 + WebAPI 基本身份验证

[英].NET CORE 2.2 Identity + Basic Auth for WebAPI

I am developing a software which contains User-Interfaces and APIs.我正在开发一个包含用户界面和 API 的软件。 For the authentication and authorization i have used .NET CORE Identity 2.2!对于身份验证和授权,我使用了 .NET CORE Identity 2.2!

I works very well.我工作得很好。 Now i have API functions which have two different requirements: 1. API Endpoint which is used by User-Interfaces (AJAX calls and so on...) 2. API Endpoint which could be used by other Software现在我有 API 函数,它们有两个不同的要求:1. 用户界面使用的 API 端点(AJAX 调用等...) 2. 其他软件可以使用的 API 端点

Therefore i would like to use two different Authorize-Methods.因此我想使用两种不同的授权方法。 For point 1 i use the .NET CORE Identity authorization and authentication.对于第 1 点,我使用 .NET CORE Identity 授权和身份验证。 And for point 2 i would like to use BASIC AUTH对于第 2 点,我想使用 BASIC AUTH

How could i configure these different Authorize-Methods.我如何配置这些不同的授权方法。 Here is a sample code:这是一个示例代码:

BASIC AUTH CODE基本授权码

  1. Try to add Service-Support for BasuicAuth in ConfigureServices services.AddAuthentication("BasicAuth").AddScheme<AuthenticationSchemeOptions, BasicAuthHandler>("BasicAuth", null);尝试在 ConfigureServices services.AddAuthentication("BasicAuth").AddScheme<AuthenticationSchemeOptions, BasicAuthHandler>("BasicAuth", null);添加对 BasuicAuth 的服务支持services.AddAuthentication("BasicAuth").AddScheme<AuthenticationSchemeOptions, BasicAuthHandler>("BasicAuth", null);

  2. Build Basic Auth Handler构建基本身份验证处理程序

    public class BasicAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions> { IConfiguration _configuration; /// <summary> /// Constructor /// </summary> /// <param name="options"></param> /// <param name="logger"></param> /// <param name="encoder"></param> /// <param name="clock"></param> /// <param name="configuration"></param> public BasicAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IConfiguration configuration) : base(options, logger, encoder, clock) { _configuration = configuration; } /// <summary> /// Handels the Authentication by using Basic Auth /// --> Checks the configured values by /// </summary> /// <returns></returns> protected override async Task<AuthenticateResult> HandleAuthenticateAsync() { if (!Request.Headers.ContainsKey("Authorization")) { return AuthenticateResult.Fail("Missing Authorization Header"); } try { var authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]); var credentialsByes = Convert.FromBase64String(authHeader.Parameter); var credentials = Encoding.UTF8.GetString(credentialsByes).Split(':'); var configuredUserName = _configuration["BasicAuth:Username"]; var configuredPassword = _configuration["BasicAuth:Password"]; if (configuredUserName.Equals(credentials[0]) & configuredPassword.Equals(credentials[1])) { var claims = new[] { new Claim(ClaimTypes.Name, credentials[0]) }; var identity = new ClaimsIdentity(claims, Scheme.Name); var principal = new ClaimsPrincipal(identity); var ticket = new AuthenticationTicket(principal, Scheme.Name); return AuthenticateResult.Success(ticket); } else { return AuthenticateResult.Fail("Invalid Credentials"); } } catch { return AuthenticateResult.Fail("Invalid Authorization Header"); } } }
  3. Try to add Authentication Basic-Auth to Controller尝试将 Authentication Basic-Auth 添加到 Controller

     [ApiController] [ApiVersion("1.0", Deprecated = false)] [Produces("application/json")] [Route("api/v{version:apiVersion}/[controller]")] [Authorize] public class MasterDataController : ControllerBase {...}

    The Authorize Annotation is using every-time the .NET CORE Identity Authorize授权注释每次使用 .NET CORE 身份授权时都会使用

ANOTHER CASE IS TO USE AUTHORIZE BY .NET CORE IDENTITY FOR UI-APIs另一种情况是对 UI-API 使用 .NET CORE IDENTITY 的授权

[ApiController]
[ApiVersion("1.0", Deprecated = false)]
[Produces("application/json")]
[Route("api/v{version:apiVersion}/[controller]")]
[Authorize(Roles = "SuperUser,PlantAdministrator,EndUser")]
public class UploadController : ControllerBase
{...}

This works very well - but i would like to use a combination...这很有效 - 但我想使用组合......

I found a solution.我找到了解决方案。 You could do it by add parameters to the Authorize annotation like the following:您可以通过向 Authorize 注释添加参数来实现,如下所示:

[ApiController]
[ApiVersion("1.0", Deprecated = false)]
[Produces("application/json")]
[Route("api/v{version:apiVersion}/[controller]")]
[Authorize(ActiveAuthenticationSchemes = "BasicAuth")]
public class MasterDataController : ControllerBase
{...}

If you set the ActiveAuthenticationSchemes to Basic Auth it looks for a compatible AuthenticationHandler!如果您将 ActiveAuthenticationSchemes 设置为 Basic Auth,它会寻找兼容的 AuthenticationHandler!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM