【问题标题】:Use Authorization middleware instead of AuthorizationAttribute ASPNET Core使用授权中间件而不是授权属性 ASP NET Core
【发布时间】:2017-09-16 03:24:03
【问题描述】:

我有一个专用的 IdServer 正在运行,它具有登录页面,其他应用程序会将未经身份验证的用户引导到该页面。

我目前的管道是:

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

所以所有教程都说在你的控制器上使用[Authorize]...

但是,我希望 middle 授权我的所有控制器和静态文件。

那么我该如何编写一个中间件来处理它。

我目前的设置是:

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();
}

【问题讨论】:

    标签: c# openid-connect identityserver4


    【解决方案1】:

    只需添加AuthenticationManagerChallenge

    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();
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2019-07-31
      • 2022-08-17
      • 2020-07-21
      • 2020-02-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-20
      • 1970-01-01
      • 2021-02-01
      相关资源
      最近更新 更多