2017-04-19 108 views
0

我有一個專門的IdServer運行,其中有登錄頁面,其他應用程序將啓動未經身份驗證的用戶。使用授權中間件,而不是授權屬性ASPNET核心

我現在的管道是:

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

回答

0

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