本文介绍了使用授权中间件代替AuthorizationAttribute ASPNET Core的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在运行一个专用的IdServer,该服务器具有登录页面,其他应用程序会将未经身份验证的用户引导到该登录页面.
I have a dedicated IdServer running that has the login page that other applications will boot unauthenticated users to.
我当前的管道是:
app.UseCookieAuthentication
app.UseOpenIdConnectAuthentication
app.UseDefaultFiles // because it is a SPA app
app.UseStaticFiles // the SPA app
所以所有教程都说要在控制器上使用[Authorize]
...
So all tutorials say to use [Authorize]
on your controllers...
但是,我希望中间人对我的所有控制器和静态文件进行授权.
However, I want middle to authorize all of my controllers, and static files.
那我该如何编写一个中间件来处理这个问题.
So how do I write a middleware to handle that.
我当前的设置是:
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();
}
推荐答案
只需添加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();
}
});
这篇关于使用授权中间件代替AuthorizationAttribute ASPNET Core的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!