IdentityServer4-挑战所有对 API 的请求,而不仅仅是 [授权]

2024-05-24

我有一个使用 IdentityServer4 的 ASP.Net Core 2 API。我想质询对服务器的所有请求,并在用户未经过身份验证时调用登录重定向,在身份验证后回调到特定的 URL。

默认情况下,仅当未经身份验证的用户请求受 [Authorize] 属性保护的资源时才调用登录重定向。这在我的用例中不起作用。

基本上,我想要整个应用程序的 [Authorize] 属性的功能等效,而不仅仅是特定的控制器。

做到这一点最简单的方法是什么?在 Startup.cs (services.AddAuthentication) 中配置服务时是否可以使用设置?或者在 app.UseAuthentication() 之后立即通过自定义中间件?

我尝试了以下自定义中间件,但它说未配置处理程序。

配置服务

services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority = "https://localhost:4000";
                options.ApiName = "myapi";
            });

配置

        app.UseAuthentication();

        app.Use(async (context, next) =>
        {
            if (!context.User.Identity.IsAuthenticated)
            {
               await context.ChallengeAsync(IdentityServerAuthenticationDefaults.AuthenticationScheme, new AuthenticationProperties {RedirectUri= "https://localhost:5000/" });
            }
            else { await next.Invoke(); }
        });

        app.UseMvc();

用于配置[Authorize]对于整个控制器,你可以尝试AuthorizeFilter像下面这样

            services.AddMvc(config => {
            var policy = new AuthorizationPolicyBuilder()
                     .RequireAuthenticatedUser()
                     .Build();
            config.Filters.Add(new AuthorizeFilter(policy));
                })                    
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

对于重定向,您可以尝试配置UserInteraction.LoginUrl

            services.AddIdentityServer(opt => {
                    opt.UserInteraction.LoginUrl = "/Identity/Account/LogIn";
                })
                .AddDeveloperSigningCredential()
                .AddInMemoryPersistedGrants()
                .AddInMemoryIdentityResources(Config.GetIdentityResources())
                .AddInMemoryApiResources(Config.GetApiResources())
                .AddInMemoryClients(Config.GetClients())
                .AddAspNetIdentity<IdentityUser>();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

IdentityServer4-挑战所有对 API 的请求,而不仅仅是 [授权] 的相关文章

随机推荐