public override void OnActionExecuted([NotNull] ActionExecutedContext context)
		{
			IAntiforgery antiForgery = context.HttpContext.RequestServices.GetService<IAntiforgery>();
			// We can send the request token as a JavaScript-readable cookie, 
			// and Angular will use it by default.
			AntiforgeryTokenSet tokens = antiForgery?.GetAndStoreTokens(context.HttpContext);
			if (tokens?.RequestToken == null) return;
			context.HttpContext.Response.Cookies.Append(essentialMix.Web.CookieNames.AntiForgeryToken, tokens.RequestToken, new CookieOptions
			{
				HttpOnly = false
			});
		}
Exemplo n.º 2
0
        //
        /// <summary>
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// configures the app to provide XSRF-TOKEN
        ///  Read More : [https://docs.microsoft.com/en-us/aspnet/core/security/anti-request-forgery]
        /// </summary>
        /// <param name="app"></param>
        /// <param name="antiforgery"></param>
        /// <param name="env"></param>
        public void Configure(IApplicationBuilder app, IAntiforgery antiforgery, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
                {
                    HotModuleReplacement = true
                });
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            // Configure your app to provide a token in a cookie called XSRF-TOKEN
            app.Use(next => _context =>
            {
                string path = _context.Request.Path.Value;
                if (
                    path.Contains("/api")
                    )
                {
                    // We can send the request token as a JavaScript-readable cookie,
                    // and Angular will use it by default.
                    var tokens = antiforgery.GetAndStoreTokens(_context);
                    _context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken,
                                                     new CookieOptions()
                    {
                        HttpOnly = false
                    });
                }

                return(next(_context));
            });
            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                routes.MapSpaFallbackRoute(
                    name: "spa-fallback",
                    defaults: new { controller = "Home", action = "Index" });
            });
        }
Exemplo n.º 3
0
        public void Configure(IApplicationBuilder app,
                              IAntiforgery antiforgery,
                              TodoRepository repository)
        {
            app.Use(next => context =>
            {
                if (
                    string.Equals(context.Request.Path.Value, "/", StringComparison.OrdinalIgnoreCase) ||
                    string.Equals(context.Request.Path.Value, "/index.html", StringComparison.OrdinalIgnoreCase))
                {
                    // We can send the request token as a JavaScript-readable cookie, and Angular will use it by default.
                    var tokens = antiforgery.GetAndStoreTokens(context);
                    context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken,
                                                    new CookieOptions()
                    {
                        HttpOnly = false
                    });
                }

                return(next(context));
            });

            app.UseDefaultFiles();
            app.UseStaticFiles();

            app.Map("/api/items", a => a.Run(async context =>
            {
                if (string.Equals("GET", context.Request.Method, StringComparison.OrdinalIgnoreCase))
                {
                    var items = repository.GetItems();
                    await context.Response.WriteAsync(JsonConvert.SerializeObject(items));
                }
                else if (string.Equals("POST", context.Request.Method, StringComparison.OrdinalIgnoreCase))
                {
                    // This will throw if the token is invalid.
                    await antiforgery.ValidateRequestAsync(context);

                    var serializer = new JsonSerializer();
                    using (var reader = new JsonTextReader(new StreamReader(context.Request.Body)))
                    {
                        var item = serializer.Deserialize <TodoItem>(reader);
                        repository.Add(item);
                    }

                    context.Response.StatusCode = (int)HttpStatusCode.NoContent;
                }
            }));
        }
Exemplo n.º 4
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IAntiforgery antiforgery)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                //app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseStaticFiles();

            app.UseIdentityServer();

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            // Preceding code ommitted.
            app.UseCors(builder => builder
                        .AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials());

            app.Use(next => context =>
            {
                string path = context.Request.Path.Value;

                // The request token can be sent as a JavaScript-readable cookie,
                // and Angular uses it by default.
                var tokens = antiforgery.GetAndStoreTokens(context);
                context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken,
                                                new CookieOptions()
                {
                    HttpOnly = false
                });

                return(next(context));
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
        public Task Invoke(HttpContext httpContext)
        {
            if (httpContext.Request.Path.HasValue)
            {
                var token = _antiForgeryService.GetAndStoreTokens(httpContext);

                httpContext.Response.Cookies.Append(
                    "cac-id",
                    token.RequestToken,
                    new CookieOptions {
                    HttpOnly = false, Secure = false, SameSite = SameSiteMode.Strict
                });
            }

            return(_next(httpContext));
        }
Exemplo n.º 6
0
    public static IHtmlContent GetHtml(this IAntiforgery antiforgery, HttpContext httpContext)
    {
        if (antiforgery == null)
        {
            throw new ArgumentNullException(nameof(antiforgery));
        }

        if (httpContext == null)
        {
            throw new ArgumentNullException(nameof(httpContext));
        }

        var tokenSet = antiforgery.GetAndStoreTokens(httpContext);

        return(new InputContent(tokenSet));
    }
Exemplo n.º 7
0
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            base.OnResultExecuting(context);

            if (!context.Cancel)
            {
                var tokens = antiforgery.GetAndStoreTokens(context.HttpContext);

                context.HttpContext.Response.Cookies.Append(
                    CookieName,
                    tokens.RequestToken,
                    new CookieOptions {
                    HttpOnly = false
                });
            }
        }
        public async Task <bool> Post()
        {
            await m_signInManager.SignOutAsync();

            //We must update the anti-forgery token as the token is bound to the logged in user
            //https://github.com/aspnet/Antiforgery/issues/93

            //Remove the user as we are logging off
            m_httpContextAccessor.HttpContext.User = null;
            //Now generate a new token
            var tokens = m_antiforgery.GetAndStoreTokens(m_httpContextAccessor.HttpContext);

            m_httpContextAccessor.HttpContext.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken);

            return(true);
        }
Exemplo n.º 9
0
        public static void AddAntiforgeryCookies(this IAntiforgery antiforgery, HttpContext context)
        {
            AntiforgeryTokenSet tokenSet = antiforgery.GetAndStoreTokens(context);

            context.
            Response.
            Cookies.
            Append(
                "XSRF-TOKEN",
                tokenSet.RequestToken,
                new CookieOptions()
            {
                // Allows client side scripts to access cookie
                HttpOnly = false
            });
        }
    public async Task <JsonResult> GetAuthSession()
    {
        return(await _apiResponseHelper.RunWithResultAsync(async() =>
        {
            var member = await _domainRepository.ExecuteQueryAsync(new GetCurrentMemberSummaryQuery());
            var token = _antiforgery.GetAndStoreTokens(HttpContext);

            var sessionInfo = new
            {
                Member = member,
                AntiForgeryToken = token.RequestToken
            };

            return sessionInfo;
        }));
    }
Exemplo n.º 11
0
        public void Configure(IApplicationBuilder app,
                              IHostingEnvironment env, DataContext context,
                              IdentityDataContext identityContext,
                              UserManager <IdentityUser> userManager,
                              RoleManager <IdentityRole> roleManager,
                              IAntiforgery antiforgery)
        {
            //app.UseDeveloperExceptionPage();
            //app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions {
            //    HotModuleReplacement = true
            //});

            app.UseStaticFiles();
            app.UseSession();
            app.UseAuthentication();

            app.Use(nextDelegate => requestContext => {
                if (requestContext.Request.Path.StartsWithSegments("/api") ||
                    requestContext.Request.Path.StartsWithSegments("/"))
                {
                    requestContext.Response.Cookies.Append("XSRF-TOKEN",
                                                           antiforgery.GetAndStoreTokens(requestContext).RequestToken);
                }
                return(nextDelegate(requestContext));
            });

            app.UseMvc(routes => {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                routes.MapSpaFallbackRoute("angular-fallback",
                                           new { controller = "Home", action = "Index" });
            });

            if ((Configuration["INITDB"] ?? "false") == "true")
            {
                System.Console.WriteLine("Preparing Database...");
                context.Database.Migrate();
                SeedData.SeedDatabase(context);
                identityContext.Database.Migrate();
                IdentitySeedData.SeedDatabase(identityContext,
                                              userManager, roleManager).GetAwaiter().GetResult();
                System.Console.WriteLine("Database Preparation Complete");
                System.Environment.Exit(0);
            }
        }
Exemplo n.º 12
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IAntiforgery antiforgery)
        {
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
                //app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
                //{
                //  HotModuleReplacement = true
                //});
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseMyMiddleware();
            //app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });

            //add authentication
            app.UseAuthentication();

            app.Use(async(context, next) =>
            {
                // XSRF-TOKEN used by angular in the $http if provided
                var tokens = antiforgery.GetAndStoreTokens(context);
                context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken);
                await next();
            });
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=IndexPage}/{id?}");
                //template: "{controller=Home}/{action=Index}/{id?}");

                routes.MapSpaFallbackRoute(
                    name: "spa-fallback",
                    defaults: new { controller = "Home", action = "IndexPage" });
            });
        }
Exemplo n.º 13
0
        public void OnGet()
        {
            AntiForgeryToken = _antiforgery.GetAndStoreTokens(HttpContext).RequestToken;

            if (_configuration.GetSection("Runtime").Exists())
            {
                Runtime = _configuration.GetSection("Runtime").Value;
            }

            if (Runtime != "WebAssembly" && _configuration.GetSection("RenderMode").Exists())
            {
                RenderMode = (RenderMode)Enum.Parse(typeof(RenderMode), _configuration.GetSection("RenderMode").Value, true);
            }

            var assemblies = AppDomain.CurrentDomain.GetOqtaneAssemblies();

            foreach (Assembly assembly in assemblies)
            {
                ProcessHostResources(assembly);
                ProcessModuleControls(assembly);
                ProcessThemeControls(assembly);
            }

            // if framework is installed
            if (!string.IsNullOrEmpty(_configuration.GetConnectionString("DefaultConnection")))
            {
                var alias = _tenantManager.GetAlias();
                if (alias != null)
                {
                    // if culture not specified
                    if (HttpContext.Request.Cookies[CookieRequestCultureProvider.DefaultCookieName] == null)
                    {
                        // set default language for site if the culture is not supported
                        var languages = _languages.GetLanguages(alias.SiteId);
                        if (languages.Any() && languages.All(l => l.Code != CultureInfo.CurrentUICulture.Name))
                        {
                            var defaultLanguage = languages.Where(l => l.IsDefault).SingleOrDefault() ?? languages.First();
                            SetLocalizationCookie(defaultLanguage.Code);
                        }
                        else
                        {
                            SetLocalizationCookie(_localizationManager.GetDefaultCulture());
                        }
                    }
                }
            }
        }
Exemplo n.º 14
0
        public async Task Invoke(HttpContext context, IAntiforgery antiforgery)
        {
            if (httpVerbs.Contains(context.Request.Method, StringComparer.OrdinalIgnoreCase))
            {
                if (context.User.Identity.IsAuthenticated)
                {
                    var tokens = antiforgery.GetAndStoreTokens(context);

                    context.Response.Cookies.Append(requestTokenCookieName, tokens.RequestToken, new CookieOptions()
                    {
                        HttpOnly = false
                    });
                }
            }

            await next.Invoke(context);
        }
Exemplo n.º 15
0
        public IActionResult GetAntiForgeryToken()
        {
            var tokens = _antiForgery.GetAndStoreTokens(HttpContext);

            Response.Cookies.Append("XSRF-REQUEST-TOKEN", tokens.RequestToken, new Microsoft.AspNetCore.Http.CookieOptions
            {
                HttpOnly = false,
                Secure   = true
            });
            return(NoContent());

            //return Ok(new
            //{
            //    token = tokens.RequestToken,
            //    tokenName = tokens.HeaderName
            //}, InfoMessages.CommonInfoMessage);
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IAntiforgery antiforgery)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStaticFiles();
            if (!env.IsDevelopment())
            {
                app.UseSpaStaticFiles();
            }

            app.Use((context, next) =>
            {
                // return current accessed path
                string path = context.Request.Path.Value;

                if (path.IndexOf("/api/", StringComparison.OrdinalIgnoreCase) != -1)
                {
                    var tokens = antiforgery.GetAndStoreTokens(context);
                    context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken,
                                                    new CookieOptions()
                    {
                        HttpOnly = false
                    });
                }

                return(next());
            });

            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
            });
            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });
        }
Exemplo n.º 17
0
        public async void Configure(IApplicationBuilder app,
                                    IHostingEnvironment env, ILoggerFactory loggerFactory,
                                    IAntiforgery antiforgery)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            // app.UseDeveloperExceptionPage();
            // app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions {
            //     HotModuleReplacement = true
            // });

            app.UseStaticFiles();
            app.UseSession();
            app.UseIdentity();

            app.Use(nextDelegate => context => {
                if (context.Request.Path.StartsWithSegments("/api") ||
                    context.Request.Path.StartsWithSegments("/"))
                {
                    context.Response.Cookies.Append("XSRF-TOKEN",
                                                    antiforgery.GetAndStoreTokens(context).RequestToken);
                }
                return(nextDelegate(context));
            });

            app.UseMvc(routes => {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                routes.MapSpaFallbackRoute("angular-fallback",
                                           new { controller = "Home", action = "Index" });
            });

            if ((Configuration["INITDB"] ?? "false") == "true")
            {
                System.Console.WriteLine("Preparing Database...");
                SeedData.SeedDatabase(app.ApplicationServices
                                      .GetRequiredService <DataContext>());
                await IdentitySeedData.SeedDatabase(app);

                System.Console.WriteLine("Database Preparation Complete");
                System.Environment.Exit(0);
            }
        }
        /// <summary>
        /// Adds an antiforgery cookie to the response.
        /// </summary>
        /// <param name="app">Application builder instance.</param>
        /// <param name="antiforgery">Antiforgery service.</param>
        /// <param name="cookieName">Name of the cookie where the token will be added.</param>
        public static void UseAntiforgeryCookieMiddleware(this IApplicationBuilder app,
                                                          IAntiforgery antiforgery,
                                                          string cookieName = "XSRF-TOKEN")
        {
            app.Use(async(context, next) =>
            {
                var tokens = antiforgery.GetAndStoreTokens(context);
                context.Response.Cookies.Append(cookieName,
                                                tokens.RequestToken,
                                                new CookieOptions()
                {
                    HttpOnly = false
                });

                await next();
            });
        }
Exemplo n.º 19
0
        public async Task InvokeAsync(HttpContext context)
        {
            string path = context.Request.Path.Value;

            if (string.Equals(path, "/admin-board", StringComparison.OrdinalIgnoreCase))
            {
                // The request token can be sent as a JavaScript-readable cookie,
                // and Angular uses it by default.
                //  angular 会自动将 cookie 中 XSRF-TOKEN 的防伪内容在请求时自动加在 X-XSRF-TOKEN 请求头上
                //  服务器接受到请求时会进行防伪检查,在 LOPController 的特性 [AutoValidateAntiforgeryToken] 中指定
                //  若不需要进行防伪检查,可在不需要检查的控制器上添加特性 [IgnoreAntiforgeryToken]
                var tokens = _antiforgery.GetAndStoreTokens(context);
                context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken);
            }

            await _next(context);
        }
Exemplo n.º 20
0
        /// <summary>
        /// The request token can be sent as a JavaScript-readable cookie,
        /// </summary>
        /// <param name="httpContext">current context</param>
        public void SetAntiForgeryCookie(HttpContext httpContext)
        {
            if (httpContext == null)
            {
                return;
            }
            var tokens = _antiForgery.GetAndStoreTokens(httpContext);

            httpContext.Response.Cookies.Append(
                "X-XSRF-TOKEN", tokens.RequestToken,
                new CookieOptions()
            {
                HttpOnly = false,                         // need to be false, is needed by the javascript front-end
                SameSite = SameSiteMode.Lax,
                Secure   = httpContext.Request.IsHttps
            });
        }
            protected override object Handle(Query request)
            {
                try
                {
                    var tokens = _antiforgery.GetAndStoreTokens(request.HttpContext);

                    return(new {
                        token = tokens.RequestToken,
                        tokenName = tokens.HeaderName
                    });
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
            }
Exemplo n.º 22
0
        /// <summary>
        /// Invokes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            var tokens = _antiAntiforgery.GetAndStoreTokens(context);
            var antiForgeryCookieOption = new CookieOptions
            {
                HttpOnly = false,
                SameSite = SameSiteMode.None
            };

            if (_securityConfiguration.CookieDomain != null)
            {
                antiForgeryCookieOption.Domain = _securityConfiguration.CookieDomain;
            }
            context.Response.Cookies.Append(AntiForgeryRequestToken, tokens.RequestToken,
                                            antiForgeryCookieOption);
            await _next(context);
        }
Exemplo n.º 23
0
        public async Task <IActionResult> Authenticate([FromBody] LoginViewModel loginViewModel)
        {
            var user = await _usersService.Authenticate(loginViewModel);

            if (user == null)
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }

            HttpContext.User = await _applicationSignInManager.CreateUserPrincipalAsync(user);

            var tokens = _antiforgery.GetAndStoreTokens(HttpContext);

            Response.Headers.Add("Access-Control-Expose-Headers", "XSRF-REQUEST-TOKEN");
            Response.Headers.Add("XSRF-REQUEST-TOKEN", tokens.RequestToken);
            return(Ok(user));
        }
Exemplo n.º 24
0
        public ActionResult <AuthInfoModel> GetInfo()
        {
            var tokens = _antiForgery.GetAndStoreTokens(HttpContext);

            HttpContext.Response.Cookies.Append(
                "XSRF-TOKEN",
                tokens.RequestToken,
                new CookieOptions()
            {
                HttpOnly = false
            });                                          //allow JS to grab the cookie to put it in the request header

            return(new AuthInfoModel
            {
                Name = User.FindFirst("name").Value
            });
        }
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            var statusCodeReExecuteFeature = context.HttpContext.Features.Get <IStatusCodeReExecuteFeature>();

            //Reissue antiforgery cookies for follow cases:
            //- when is requested only an ASP.NET View. Since set cookies for each requests such Assets or file resources can leads to stop working the output cache middleware for that controllers
            //- when there are no errors or inner status codes ReExecute occurs (404, 500 etc) (IStatusCodeReExecuteFeature is presents). Since this can leads for reissue an antiforgery cookies .AspNetCore.Antiforgery without AspNetCore.Identity.Application
            //that can leads for 400 errors for antiforgery validation due to different User and passed antiforgery tokens from cookies and request headers or form field
            if (context.Result is ViewResult viewResult && statusCodeReExecuteFeature == null)
            {
                var tokens = antiforgery.GetAndStoreTokens(context.HttpContext);
                context.HttpContext.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions()
                {
                    HttpOnly = false, IsEssential = true
                });
            }
        }
Exemplo n.º 26
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IAntiforgery antiforgery)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseApplicationInsightsRequestTelemetry();

            app.UseApplicationInsightsExceptionTelemetry();

            app.UseCors("AllowFromAll");


            // Add proper support for XSRF token (cookies)
            app.Use(next => context =>
            {
                if (context.Request.Path.Value.StartsWith("/api", StringComparison.OrdinalIgnoreCase))
                {
                    var tokens = antiforgery.GetAndStoreTokens(context);
                    context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken,
                                                    new CookieOptions()
                    {
                        HttpOnly = false
                    });
                }

                return(next(context));
            });

            app.UseDefaultFiles();
            //app.UseStaticFiles();


            app.UseMvc();

            app.UseSwaggerGen();
            app.UseSwaggerUi();

            if (env.IsDevelopment())
            {
                // Ensure default data is available during development.
                using (var serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope())
                {
                    serviceScope.ServiceProvider.GetService <AwesomeContext>().EnsureSeedData();
                }
            }
        }
Exemplo n.º 27
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IAntiforgery antiforgery)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }



            //add antiforgery token to cookies
            app.Use(next => context =>
            {
                if (
                    string.Equals(context.Request.Path.Value, "/", StringComparison.OrdinalIgnoreCase) ||
                    string.Equals(context.Request.Path.Value, "/index", StringComparison.OrdinalIgnoreCase))
                {
                    var token = antiforgery.GetAndStoreTokens(context);
                    context.Response.Cookies.Append("X-XSRF-TOKEN", token.RequestToken, new CookieOptions
                    {
                        HttpOnly = false
                    });
                }


                return(next(context));
            });

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseAuthentication();//add authentication module
            app.UseCookiePolicy();
            app.UseSession();


            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
        public Task Invoke(HttpContext context)
        {
            var path = context.Request.Path.Value;

            if (path != null && !path.StartsWith("/api/", StringComparison.OrdinalIgnoreCase))
            {
                var tokens = _antiforgery.GetAndStoreTokens(context);
                context.Response.Cookies.Append(
                    key: "XSRF-TOKEN",
                    value: tokens.RequestToken,
                    options: new CookieOptions
                {
                    HttpOnly = false       // Now JavaScript is able to read the cookie
                });
            }
            return(_next(context));
        }
Exemplo n.º 29
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(
            IApplicationBuilder app,
            IWebHostEnvironment env,
            IAntiforgery antiforgery,
            IServiceProvider services)
        {
            dataStartup.Configure(app, env);
            identityStartup.Configure(app, env, services);
            apiStartup.Configure(app, env);

            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });

            app.UseAuthentication();
            app.Use(next => context =>
            {
                string path = context.Request.Path.Value;

                if (path.ToLower().Contains("/account"))
                {
                    //         if (
                    // string.Equals(path, "/", StringComparison.OrdinalIgnoreCase) ||
                    // string.Equals(path, "/index.html", StringComparison.OrdinalIgnoreCase)) {
                    // The request token can be sent as a JavaScript-readable cookie,
                    // and Angular uses it by default.
                    var tokens = antiforgery.GetAndStoreTokens(context);
                    context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken,
                                                    new CookieOptions()
                    {
                        HttpOnly = false
                    });
                }

                return(next(context));
            }
                    );

            app.UseHttpsRedirection();
            // app.UseMiddleware<AntiForgeryMiddleware>("XSRF-TOKEN");
            app.UseJwtTokenMiddleware();
            app.UseCookiePolicy();
            app.UseGraphiQl();
        }
Exemplo n.º 30
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IAntiforgery antiforgery)
        {
            app.UseResponseCompression();

            if (env.IsDevelopment())
            {
                //app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
                //app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseAuthentication();

            app.Use(next => context =>
            {
                if (context.Request.Method == "GET")
                {
                    var tokens = antiforgery.GetAndStoreTokens(context);
                    context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken,
                                                    new CookieOptions {
                        HttpOnly = false
                    });
                }

                return(next(context));
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(name: "default", template: "{controller}/{action}/{id?}");
            });

            app.UseCookiePolicy();

            app.UseBlazor <BlazorApplication1.Client.Startup>();
        }
Exemplo n.º 31
0
        public void Configure(IApplicationBuilder app, IAntiforgery antiforgery, IOptions<AntiforgeryOptions> options, TodoRepository repository)
        {
            app.Use(next => context =>
            {
                if (
                    string.Equals(context.Request.Path.Value, "/", StringComparison.OrdinalIgnoreCase) ||
                    string.Equals(context.Request.Path.Value, "/index.html", StringComparison.OrdinalIgnoreCase))
                {
                    // We can send the request token as a JavaScript-readable cookie, and Angular will use it by default.
                    var tokens = antiforgery.GetAndStoreTokens(context);
                    context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions() { HttpOnly = false });
                }

                return next(context);
            });

            app.UseDefaultFiles();
            app.UseStaticFiles();

            app.Map("/api/items", a => a.Run(async context =>
            {
                if (string.Equals("GET", context.Request.Method, StringComparison.OrdinalIgnoreCase))
                {
                    var items = repository.GetItems();
                    await context.Response.WriteAsync(JsonConvert.SerializeObject(items));
                }
                else if (string.Equals("POST", context.Request.Method, StringComparison.OrdinalIgnoreCase))
                {
                    // This will throw if the token is invalid.
                    await antiforgery.ValidateRequestAsync(context);

                    var serializer = new JsonSerializer();
                    using (var reader = new JsonTextReader(new StreamReader(context.Request.Body)))
                    {
                        var item = serializer.Deserialize<TodoItem>(reader);
                        repository.Add(item);
                    }

                    context.Response.StatusCode = 204;
                }
            }));
        }