1.配置两种认证方式

    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            services.AddAuthentication(options =>
            {
                options.DefaultScheme = "Cookies";
                options.DefaultChallengeScheme = "oidc";
            })

            .AddCookie("Cookies")
            .AddOpenIdConnect("oidc", options =>
            {
                options.SignInScheme = "Cookies";
                options.Authority = GZSetting.ApiAuthIp;
                options.RequireHttpsMetadata = false;
                options.ClientId = GZSetting.MvcClientId;
                options.ClientSecret = GZSetting.ClientSecret;
                options.ResponseType = "code id_token";
                options.Scope.Clear();
                options.Scope.Add("openid");
                options.Scope.Add(GZSetting.ApiName);
                //options.Scope.Add("roles");
                options.SaveTokens = true;
                options.GetClaimsFromUserInfoEndpoint = true;

                options.ClaimActions.MapUniqueJsonKey("role", "role");

            })
                .AddIdentityServerAuthentication("Bearer", options =>
                 {
                     options.RequireHttpsMetadata = false;
                     options.Authority = GZSetting.ApiAuthIp;
                     options.ApiName = GZSetting.ApiName;
                 });

 

2.配置授权策略

 services.AddAuthorization(option =>
            {
                //默认 只写 [Authorize],表示使用oidc进行认证
                option.DefaultPolicy = new AuthorizationPolicyBuilder("oidc").RequireAuthenticatedUser().Build();
//ApiController使用这个  [Authorize(Policy = "ApiPolicy")],使用jwt认证方案
                option.AddPolicy("ApiPolicy", policy =>
                {
                    policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
                    policy.RequireAuthenticatedUser();
                });
            });

 

3.给Webapi的控制器添加授权标签

    [Authorize(Policy = "ApiPolicy")]
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TestInfoController : ControllerBase

 4.如果一个控制器要求Jwt认证或OpenId认证(当在普通控制器中写Api接口时,就需要这样写)

[Authorize(AuthenticationSchemes = "Bearer,Cookies")]
public class KeyValueStoresController : Controller