【问题标题】:Multiple authentication methods in asp.Net core 2.2asp.Net core 2.2中的多种身份验证方法
【发布时间】:2019-06-13 02:57:57
【问题描述】:

有没有办法在 .net 核心中使用 JWT 不记名身份验证和自定义身份验证方法?我希望所有操作都默认为 JWT,除了在少数情况下我想使用自定义身份验证标头。

【问题讨论】:

标签: authentication asp.net-core .net-core


【解决方案1】:

我终于想通了。此示例默认使用 JWT 身份验证,在某些极少数情况下使用自定义身份验证。请注意,根据我的阅读,微软似乎不鼓励编写自己的身份验证。请自行承担使用风险。

首先,将此代码添加到 startup.cs 的 ConfigureServices 方法,以确保全局应用身份验证。

services.AddMvc(options => 
    {
        var policy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .Build();
        options.Filters.Add(new AuthorizeFilter(policy));
    })

然后,添加此项以配置您希望使用的方案(在我们的示例中为 JWT 和自定义)。

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    // Jwt Authentication
    .AddJwtBearer(options =>
    {
        options.Audience = ".......";
        options.Authority = "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_...";
    })
    // Custom auth
    .AddScheme<CustomAuthOptions, 
        CustomAuthHandler>(CustomAuthOptions.DefaultScheme, options => { });

接下来创建一个类来保存您的自定义身份验证选项:

public class CustomAuthOptions : AuthenticationSchemeOptions
{
    public const string Scheme = "custom auth";
    public const string CustomAuthType = "custom auth type";
}

最后,添加一个身份验证处理程序来实现自定义身份验证逻辑。

public class CustomAuthHandler : AuthenticationHandler<CustomAuthOptions>
{
    public CustomAuthHandler(
        IOptionsMonitor<CustomAuthOptions> options, 
        ILoggerFactory logger, 
        UrlEncoder encoder, 
        ISystemClock clock) : base(options, logger, encoder, clock)
    {
    }

    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        // Auth logic goes here
        if (!Request.Headers....) 
        {
            return Task.FromResult(AuthenticateResult.Fail("Authentication Failed."));
        }

        // Create authenticated user
        ClaimsPrincipal principal = .... ;

        List<ClaimsIdentity> identities = 
            new List<ClaimsIdentity> {
                new ClaimsIdentity(CustomAuthOptions.CustomAuthType)};

        AuthenticationTicket ticket = 
            new AuthenticationTicket(
                new ClaimsPrincipal(identities), CustomAuthOptions.Scheme);

        return Task.FromResult(AuthenticateResult.Success(ticket));
    }
}

最后,为了将它们结合在一起,为您希望对其使用自定义授权的操作添加一个授权属性。

[HttpGet]
[Authorize(AuthenticationSchemes = CustomAuthOptions.Scheme)]
public HttpResponseMessage Get()
{
    ....
}

现在 JWT 身份验证将自动应用于所有操作,并且自定义身份验证将仅添加到 Authorize 属性设置为自定义方案的操作。

我希望这对某人有所帮助。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-07-10
  • 2019-08-31
  • 2019-09-06
  • 2022-01-04
  • 2019-12-13
  • 1970-01-01
  • 2019-10-18
  • 2020-03-21
相关资源
最近更新 更多