Loading

Prevent XSRF/CSRF attacks(防止 XSRF/CSRF 攻击)

添加 nuget 包  Microsoft.AspNetCore.Antiforgery 

修改 Startup 类代码

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAntiforgery(options =>
            {
                options.Cookie.Name = "AntiForgery";
                options.Cookie.Domain = "localhost";
                options.Cookie.Path = "/";
                options.FormFieldName = "Antiforgery";
                options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
            });
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory logger, IConfiguration configuration, IAntiforgery antiForgery)
        {
            //These are the four default services available at Configure
            app.Run(async context =>
            {
                if (HttpMethods.IsPost(context.Request.Method))
                {
                    await antiForgery.ValidateRequestAsync(context);        
                    await context.Response.WriteAsync("Response validated with anti forgery");
                    return;
                }
                
                var token = antiForgery.GetAndStoreTokens(context);
               
                context.Response.Headers.Add("ContentType", "text/html");
                await context.Response.WriteAsync($@"
                <html>
                <body>
                    View source to see the generated anti forgery token
                    <form method=""post"">
                        <input type=""hidden"" name=""{token.FormFieldName}"" value=""{token.RequestToken}"" />
                        <input type=""submit"" value=""Push""/>
                    </form>
                </body>
                </html>   
                ");
            });
        }

 

posted @ 2018-10-22 15:12  myEsn2E9  阅读(11)  评论(0)    收藏  举报