authentication - asp.Net core 2.2中的多种认证方式

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

有没有办法在 .net core 中使用 JWT 承载身份验证和自定义身份验证方法?我希望所有操作都默认为 JWT,但在少数情况下我想使用自定义身份验证 header 。

最佳答案

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

首先,将此代码添加到 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 属性设置为自定义方案的操作。

我希望这对某人有帮助。

关于authentication - asp.Net core 2.2中的多种认证方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54260837/

相关文章:

authentication - 使用 Vanilla 论坛使用 Cookie 对用户进行身份验证

java - hql查询的返回类型

c# - IoC 容器 - 仅为特定服务注入(inject)新的 DbContext 实例

c# - .net core 5 中具有参数依赖关系的全局过滤器

.net - 视频编辑付费或免费,但不是 FFMpeg

c# - 如何在 docker 容器中运行 asp.net 核心应用程序?

c# - 如何在 .NET Core 类库中引用 Visual Studio 共享项目

javascript - 用于受密码保护的网站的 nodejs 网络抓取工具

asp.net-core - XUnit ASP.Net Core WebAPI 测试中 EnsureSuccessStatusCode 和 Assert.Equal(HttpStatusCode.OK, response.StatusCode) 之间的区别

ios - Box API 身份验证 - Objective-c iOS