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

问题描述

我需要在 ASP.NET Core 2.0 MVC应用程序中支持两种身份验证类型:

I need to support two authentication types in ASP.NET Core 2.0 MVC application:

  1. AddIdentityServerAuthentication
  2. AddOpenIdConnect

ASP.NET Core 1.0 版本中,这非常容易.但是在 2.0版版本中,语法已更改.这是我的代码:

It was very easy in ASP.NET Core 1.0 version. But in version 2.0 version syntax changed. This is my code:

services.AddAuthentication(o =>
    {
        o.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        o.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        o.DefaultAuthenticateScheme = OpenIdConnectDefaults.AuthenticationScheme;
    }).AddIdentityServerAuthentication(options =>
    {
        options.Authority = PlatformConfiguration.IdentityServerUri;
        options.RequireHttpsMetadata = false;
        options.SaveToken = true;
        options.ApiSecret = "somesecret";
        options.ApiName = "some_api";
    })
    .AddCookie()
    .AddOpenIdConnect(o =>
    {
        o.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        o.Authority = PlatformConfiguration.IdentityServerUri;
        o.RequireHttpsMetadata = false;
        o.ClientId = "some_viewer";
        o.UseTokenLifetime = true;
        o.ResponseType = "id_token token";
        o.Scope.Add("openid");
        o.Scope.Add("roles");
        o.Scope.Add("profile");
        o.SaveTokens = true;
        o.TokenValidationParameters = new TokenValidationParameters
        {
            NameClaimType = JwtClaimTypes.Name,
            RoleClaimType = JwtClaimTypes.Role
        };
    });

services.AddAuthorization();

但是以这种方式,承载身份验证不起作用.由于存在以下默认方案: DefaultChallengeScheme DefaultAuthenticateScheme .
如何定义几种身份验证方案?

But in this way, the Bearer authentication doesn't work. Because of default schemes: DefaultChallengeScheme, DefaultAuthenticateScheme.
How to define several authentication schemes?

推荐答案

我添加了属性

[Authorize(AuthenticationSchemes = IdentityServerAuthenticationDefaults.AuthenticationScheme + "," + OpenIdConnectDefaults.AuthenticationScheme)]

现在我有两种身份验证方案.

And now I have two authentication schemes.

在启动中使用此代码的更灵活的解决方案:

More flexible solution to use this code in Startup:

if (UseAuthorization)
{
    var policy = new AuthorizationPolicyBuilder(IdentityServerAuthenticationDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme)
        .RequireAuthenticatedUser()
        .Build();

    options.Filters.Add(new AuthorizeFilter(policy));
}

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

08-20 08:25