11using System ;
22using Microsoft . AspNetCore . Builder ;
33using Microsoft . AspNetCore . Hosting ;
4+ using Microsoft . AspNetCore . Antiforgery ;
5+
46using Microsoft . AspNetCore . SpaServices . Webpack ;
57using Microsoft . Extensions . Configuration ;
68using Microsoft . Extensions . DependencyInjection ;
79using Microsoft . Extensions . Logging ;
10+ using Microsoft . AspNetCore . Authentication . Cookies ;
811using Microsoft . EntityFrameworkCore ;
912using Angular2Spa . Models ;
13+ using Microsoft . AspNetCore . Http ;
1014
1115namespace Angular2Spa
1216{
@@ -47,6 +51,8 @@ public void ConfigureServices(IServiceCollection services)
4751 services . AddMvc ( ) ;
4852 services . AddMemoryCache ( ) ;
4953
54+ services . AddAntiforgery ( options => options . HeaderName = "X-XSRF-TOKEN" ) ;
55+
5056 //Adding SignalR Service
5157 services . AddSignalR ( options => {
5258 services . AddMemoryCache ( ) ;
@@ -59,7 +65,7 @@ public void ConfigureServices(IServiceCollection services)
5965 }
6066
6167 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
62- public void Configure ( IApplicationBuilder app , IHostingEnvironment env , ILoggerFactory loggerFactory )
68+ public void Configure ( IApplicationBuilder app , IHostingEnvironment env , ILoggerFactory loggerFactory , IAntiforgery antiforgery )
6369 {
6470 loggerFactory . AddConsole ( Configuration . GetSection ( "Logging" ) ) ;
6571 loggerFactory . AddDebug ( ) ;
@@ -86,6 +92,20 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerF
8692 app . UseExceptionHandler ( "/Home/Error" ) ;
8793 }
8894
95+ // CSRF / XSRF Token
96+ app . Use ( async ( context , next ) =>
97+ {
98+ if ( string . Equals ( context . Request . Path . Value , "/" , StringComparison . OrdinalIgnoreCase ) )
99+ {
100+ var tokens = antiforgery . GetAndStoreTokens ( context ) ;
101+
102+ context . Response . Cookies . Append ( "XSRF-TOKEN" , tokens . RequestToken , new CookieOptions ( ) {
103+ HttpOnly = false
104+ } ) ;
105+ }
106+ await next . Invoke ( ) ;
107+ } ) ;
108+
89109 app . UseStaticFiles ( ) ;
90110
91111 // ** MVC / WebAPI Routing & default SPA fallback Routing
0 commit comments