。NET CORE 2.2身份+ WebAPI的基本身份验证

问题描述 投票:0回答:1

我正在开发一个包含用户界面和API的软件。为了进行身份验证和授权,我使用了.NET CORE Identity 2.2!

我做得很好。现在我有两个不同要求的API函数:1.用户界面(AJAX调用等)使用的API端点2.其他软件可以使用的API端点

因此,我想使用两种不同的授权方法。对于第1点,我使用.NET CORE身份授权和身份验证。对于第二点,我想使用BASIC AUTH

我该如何配置这些不同的授权方法。这是示例代码:

基本验证码

  1. 尝试在ConfigureServices中添加对BasuicAuth的服务支持services.AddAuthentication("BasicAuth").AddScheme<AuthenticationSchemeOptions, BasicAuthHandler>("BasicAuth", null);

  2. 构建基本身份验证处理程序

    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. 尝试向控制器添加身份验证基本身份验证

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

    每次使用.NET CORE身份授权时都会使用授权注释

    ] >>
  4. 另一种情况是要使用UI API的.NET核心身份进行授权

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

效果很好-但我想使用组合...

我正在开发一个包含用户界面和API的软件。为了进行身份验证和授权,我使用了.NET CORE Identity 2.2!我做得很好现在我有了具有...

c# .net-core basic-authentication asp.net-core-identity
1个回答
0
投票

我找到了解决方案。您可以通过将参数添加到Authorize批注中来实现,如下所示:

© www.soinside.com 2019 - 2024. All rights reserved.