受保护 ASP.NET Core 2 MVC 控制器中的不记名令牌授权

Bearer token authorization in a protected ASP.NET Core 2 MVC controller

我们有一个 ASP.NET Core 2 MVC 项目,它使用 IdentityServer4 来保护它的页面。常规控制器在未通过身份验证时重定向到身份服务器,这是预期的行为。我试图启用的是 public 控制器方法由用户中的 non-signed 使用访问令牌调用,该访问令牌由同一身份服务器提供给调用者。如果用户拥有有效的访问令牌,则该方法应该正常运行,否则会出现 401 错误或类似错误。

问题是,即使使用 Authorization: Bearer header 使用有效的访问令牌调用该方法,它也会被重定向到 IdentityServer。是否有可能实现我想要做的事情?我必须为此方法定义不同的授权方案吗?

这是 OIDC 配置:

void oidcOptions(OpenIdConnectOptions options)
            {
                options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

                options.Authority = openIdSettings.StsAuthority;
                options.RequireHttpsMetadata = openIdSettings.DiscoveryEndpointRequiresHttps;

                options.ClientId = openIdSettings.ClientId;
                options.ClientSecret = openIdSettings.ClientSecret;

                options.ResponseType = "code id_token";
                options.SaveTokens = true;
                options.UseTokenLifetime = true;

                options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    NameClaimType = ClaimTypes.Name,
                    RoleClaimType = ClaimTypes.Role,
                };

                options.Scope.Remove("profile");

                foreach (string scope in openIdSettings.Scopes)
                {
                    options.Scope.Add(scope.Trim());
                }
            }

            services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = AuthenticationConstants.SigninScheme;
            })
            .AddCookie(options =>
            {
                options.Cookie.Name = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddOpenIdConnect(AuthenticationConstants.SigninScheme, oidcOptions);

我已经解决了使用 AddJwtBearer("token_scheme"..) 添加新的身份验证方案作为对现有方案的补充,并使用 [Authorize(AuthenticationSchemes = "token_scheme")].

在方法上指定身份验证方案