IdentityServer4-挑战所有对API的请求,而不仅是[授权] [英] IdentityServer4- Challenge ALL requests to API not just [Authorize]
问题描述
我有一个使用IdentityServer4的ASP.Net Core 2 API.我想挑战所有对服务器的请求,如果用户未通过身份验证,则调用登录重定向,并在身份验证后回调到特定的URL.
I have an ASP.Net Core 2 API using IdentityServer4. I would like challenge ALL requests to the server and invoke the login redirect if the user is not authenticated, calling back to a specific URL after authentication.
默认设置是仅在未经身份验证的用户请求受[Authorize]属性保护的资源时才调用登录重定向.在我的用例中,这是行不通的.
The default is to invoke the login redirect only when an unauthenticated user requests a resource protected by the [Authorize] attribute. This will not work in my use case.
基本上,我希望整个应用程序都具有等同于[Authorize]属性的功能,而不仅仅是特定的控制器.
Basically, I want the functional equivalent of an [Authorize] attribute for the whole application not just specific controllers.
最简单的方法是什么?在Startup.cs(services.AddAuthentication)中配置服务时,可以使用我的设置吗?还是在app.UseAuthentication()之后通过自定义中间件?
What is the easiest way to do this? Is there a setting I can use when configuring the services in Startup.cs (services.AddAuthentication)? Or through custom middleware right after app.UseAuthentication()?
我尝试了以下自定义中间件,但说未配置处理程序.
I tried the following custom middleware but it says a handler is not configured.
ConfigureServices
ConfigureServices
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
,如下所示
For configuring [Authorize]
for the whole controllers, you could try AuthorizeFilter
like below
services.AddMvc(config => {
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
对于重定向,您可以尝试配置UserInteraction.LoginUrl
For redirecting, you could try configure UserInteraction.LoginUrl
services.AddIdentityServer(opt => {
opt.UserInteraction.LoginUrl = "/Identity/Account/LogIn";
})
.AddDeveloperSigningCredential()
.AddInMemoryPersistedGrants()
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients())
.AddAspNetIdentity<IdentityUser>();
这篇关于IdentityServer4-挑战所有对API的请求,而不仅是[授权]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!