这节我们讲解一下反伪造令牌,它是ASP.NET Core中的一项安全技术,用于防止跨站伪造请求(CSRF)攻击。在展开这个话题之前我们首先介绍一下什么是CSRF。
跨站请求伪造(CSRF)是一种针对托管在 Web 上的应用程序的攻击,恶意应用程序(通常指Web)可以影响客户端浏览器与信任该浏览器的Web 应用之间的交互。之所以有这种攻击,是因为 Web 浏览器会自动将用户身份验证令牌与每次发送给网站的请求一起打包发送。由于这种攻击利用了用户已认证的会话,它也被称为“一键攻击”或“会话骑乘”。跨站请求伪造也被称为 XSRF 或 CSRF。
<h1>Congratulations! You're a Winner!</h1> <form action="https://good-banking-site.com/api/account" method="post"> <input type="hidden" name="Transaction" value="withdraw" /> <input type="hidden" name="Amount" value="1000000" /> <input type="submit" value="Click to collect your prize!" /> </form>注意这个恶意站点的action是指向安全站点的地址,用户点击Submit提交按钮。
4. 该请求在 www.good-banking-site.example.com 服务器上运行,使用用户的身份验证上下文,并可以执行任何经过身份验证的用户被允许执行的操作。
using Microsoft.AspNetCore.Antiforgery; var builder = WebApplication.CreateBuilder(); builder.Services.AddAntiforgery(options => { options.Cookie.Name = "AntiForgery"; options.Cookie.Domain = "localhost"; options.Cookie.Path = "/"; options.FormFieldName = "Antiforgery"; options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; }); var app = builder.Build(); // 堆代码 duidaima.com //These are the four default services available at Configure app.Run(async context => { var antiForgery = context.RequestServices.GetService<IAntiforgery>(); 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.Append("Content-Type", "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> "); }); app.Run();上面代码中: