我必须保护我的Web应用程序免受CSRF的侵害,CSRF是一个.Net核心MVC Web应用程序,客户端具有Angular 9。
这是我尝试过的
// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
services.AddMvc(option => option.EnableEndpointRouting = false);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IAntiforgery antiforgery)
{
app.Use((context, next) =>
{
// CSRF cookie token generation
string path = context.Request.Path.Value;
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 });
}
// CSRF cookie token generation - end
return next.Invoke();
});
}
它正在生成XSRF-TOKEN cookie,但是Angular没有在请求中设置X-XSRF-TOKEN标头。 我没有在Angular请求部分中进行任何代码更改。
Controller.cs
[ValidateAntiForgeryToken]
[HttpPost]
public IActionResult ProduceMessage([FromBody] OncRequestData oncRequestData)
{
OncRequestData _OncRequestData = new OncRequestData();
}
在Angular应用中,我添加了一个httpintercepter来提取并发送请求标头中的令牌
export class TokenInterceptorService implements HttpInterceptor {
token: string;
constructor(private xsrfTokenExtractor: HttpXsrfTokenExtractor) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if(req.method == "POST")
{
let xsrfToken = this.xsrfTokenExtractor.getToken();
const authReq = req.clone({ headers: req.headers.set("X-XSRF-TOKEN", xsrfToken) });
return next.handle(authReq);
}else{
return next.handle(req);
}
}
现在我从服务器收到错误的请求错误(400)
答案 0 :(得分:0)
我通过进行以下更改来临时解决此问题。
public class AntiforgeryValidationMiddleware
{
private readonly RequestDelegate _next;
public AntiforgeryValidationMiddleware(RequestDelegate next)
{
_next = next;
}
/// <summary>
/// Validate incoming request for CSRF token
/// </summary>
/// <param name="httpContext"></param>
/// <param name="antiforgery"></param>
/// <returns></returns>
public async Task InvokeAsync(HttpContext httpContext, IAntiforgery antiforgery)
{
try
{
// if the POST request is not from AD2BC call back
if (httpContext.Request.Method == "POST" && !httpContext.Request.Path.Equals("/Home/Auth"))
{
await antiforgery.ValidateRequestAsync(httpContext);
}
await _next(httpContext);
}
catch (AntiforgeryValidationException exception)
{
Log.Error("CSRF token validation failed" + exception.Message);
}
}
}
请让我知道是否有人有更好的解决方案