使用授权中间件而不是AuthorizationAttribute ASPNET Core

时间:2017-04-19 18:30:04

标签: c# openid-connect identityserver4

我有一个专用的IdServer运行,它有一个登录页面,其他应用程序将启动未经身份验证的用户。

我目前的管道是:

app.UseCookieAuthentication
app.UseOpenIdConnectAuthentication
app.UseDefaultFiles // because it is a SPA app
app.UseStaticFiles // the SPA app

所以所有教程都说要在你的控制器上使用[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();
}

1 个答案:

答案 0 :(得分:3)

只需添加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();
    }
});