ASP.NET Core 2.2中的多种身份验证方法 [英] Multiple authentication methods in asp.Net core 2.2

查看:323
本文介绍了ASP.NET Core 2.2中的多种身份验证方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.net核心中是否有使用JWT承载身份验证和自定义身份验证方法的方法?除了在某些情况下要使用自定义身份验证标头的情况之外,我希望所有操作都默认为JWT.

Is there a way to use JWT bearer authentication AND a custom authentication method in .net core? I want all actions to default to JWT, except in a few cases where I want to use a custom authentication header.

推荐答案

我终于弄清楚了该怎么做.此示例默认情况下使用JWT身份验证,在某些极少数情况下使用自定义身份验证.请注意,根据我的阅读,Microsoft似乎不鼓励编写您自己的身份验证.请自担风险.

I finally figured out how to do it. This example uses JWT authentication by default and custom authentication in certain rare cases. Please note, from what I've read, Microsoft seems to discourage writing your own auth. Please use at your own risk.

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

First, add this code to the startup.cs ConfigureServices method to ensure that authentication gets applied globally.

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

然后,添加它以配置您希望使用的方案(在我们的示例中为JWT和Custom).

Then, add this to configure the schemes you wish to use (in our case JWT and Custom).

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 => { });

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

Next create a class to hold your custom authentication options:

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

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

Finally, add an authentication handler to implement the custom authentication logic.

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));
    }
}

最后,要将所有内容捆绑在一起,请向您要在其上使用自定义授权的操作添加一个authorize属性.

Finally, to tie it all together, add an authorize attribute to the actions you wish to use custom authorization on.

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

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

Now JWT authentication will automatically get applied to all actions, and custom authentication will get added to only the actions with the Authorize attribute set to the custom scheme.

我希望这对某人有帮助.

I hope this helps someone.

这篇关于ASP.NET Core 2.2中的多种身份验证方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆