【问题标题】:Bearer token authorization in a protected ASP.NET Core 2 MVC controller受保护的 ASP.NET Core 2 MVC 控制器中的不记名令牌授权
【发布时间】:2019-05-05 17:58:41
【问题描述】:

我们有一个 ASP.NET Core 2 MVC 项目,它使用 IdentityServer4 来保护它的页面。常规控制器在未经过身份验证时重定向到身份服务器,这是预期的行为。我要启用的是由非登录用户使用访问令牌调用公共控制器方法,该访问令牌由同一身份服务器提供给调用者。如果用户有一个有效的访问令牌,则该方法应该定期运行,如果没有给出 401 错误或类似的东西。

问题是,即使使用Authorization: Bearer 标头使用有效的访问令牌调用该方法,它也只会被重定向到 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);

【问题讨论】:

  • 您是否查看过将中间件映射到您尝试在 Startup.cs 中使用的路径以绕过身份服务器重定向?
  • @Tubs:是的,我有,但访问令牌由同一个身份服务器提供,因此公共方法路径也需要与身份服务器集成。我似乎忽略了我更新问题的细节,谢谢。

标签: security asp.net-core asp.net-core-mvc openid-connect asp.net-core-2.1


【解决方案1】:

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

【讨论】:

猜你喜欢
  • 2020-07-09
  • 2021-10-05
  • 2016-05-01
  • 1970-01-01
  • 2019-07-04
  • 2020-07-25
  • 1970-01-01
  • 2021-01-01
  • 1970-01-01
相关资源
最近更新 更多