Cal*_*ton 5 c# openid-connect identityserver4
我有一个专用的 IdServer 运行,它具有其他应用程序将未经身份验证的用户引导到的登录页面。
我目前的管道是:
app.UseCookieAuthentication
app.UseOpenIdConnectAuthentication
app.UseDefaultFiles // because it is a SPA app
app.UseStaticFiles // the SPA app
Run Code Online (Sandbox Code Playgroud)
所以所有的教程都说要[Authorize]在你的控制器上使用......
但是,我希望中间人授权我的所有控制器和静态文件。
那么我如何编写一个中间件来处理这个问题。
我目前的设置是:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IOptions<IdentityServerAppOptions> identityServerAppOptions)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
var serverAppOptions = identityServerAppOptions.Value;
loggerFactory.CreateLogger("Configure").LogDebug("Identity Server Authority Configured: {0}", serverAppOptions.Authority);
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = "Cookies"
});
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
AuthenticationScheme = "oidc",
SignInScheme = "Cookies",
Authority = serverAppOptions.Authority,
RequireHttpsMetadata = false,
ClientId = "Video",
SaveTokens = true
});
app.Use(async (context, next) =>
{
var authService = context.RequestServices.GetRequiredService<IAuthorizationService>();
if (!await authService.AuthorizeAsync(context.User, context, "Api"))
{
// This is as far as I have got, here we should boot them to IdServer
}
});
app.UseDefaultFiles(new DefaultFilesOptions
{
DefaultFileNames = new List<string> { "index.html" },
RequestPath = new PathString("")
});
app.UseStaticFiles(new StaticFileOptions
{
OnPrepareResponse = ctx =>
{
ctx.Context.Response.Headers.Append("Cache-Control", "no-cache");
}
});
app.UseMvc();
}
Run Code Online (Sandbox Code Playgroud)
只需要添加AuthenticationManager Challenge:
app.Use(async (context, next) =>
{
var authService = context.RequestServices.GetRequiredService<IAuthorizationService>();
if (!await authService.AuthorizeAsync(context.User, context, "Api"))
{
await context.Authentication.ChallengeAsync("oidc");
}
else
{
await next();
}
});
Run Code Online (Sandbox Code Playgroud)