1. 用户登录www.good-banking-site.example.com网站,服务器对用户进行身份验证并返回包含身份验证 Cookie 的响应。该站点容易受到攻击,因为它信任任何带有有效身份验证 Cookie 的请求。
2. 用户无访问了恶意站点:www.bad-crook-site.example.com.恶意站点包含了如下代码:
<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提交按钮。
CSRF 攻击之所以可能发生在使用 Cookie 进行身份验证的 Web 应用中,是因为:
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();
//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();
上面代码中:
[ValidateAntiForgeryToken] 特性,除了使用上面方法之外,还可以使用该特性在Action上进行验证。