Blazor WebAssembly中的防止跨站点请求伪造 (XSRF/CSRF) 攻击
这里以Asp.net Core的服务端并且Asp.net Core托管客户端为例,跨域请求的参考其他跨域设置。
在Asp.net Core中,XSRF/CSRF是通过验证http头或form表单中的字段来验证请求的。
在Asp.net Core的Startup中注入如下服务以启用防止跨站点请求伪造 (XSRF/CSRF) 攻击
services.AddAntiforgery(options =>{ options.HeaderName = "X-CSRF-TOKEN-HEADER"; options.FormFieldName = "X-CSRF-TOKEN-FORM"; });
启用如下中间件以在Cookie中写入令牌
app.Use(next=>context=> { var tokens = antiforgery.GetAndStoreTokens(context); context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken,new CookieOptions() {HttpOnly=false }); return next(context); });
在Blazor WebAssembly 客户端中注入JSRuntime用于通过js读取Cookie
@inject IJSRuntime JSRuntime
在FORM表单中附加令牌
var token = await JSRuntime.InvokeAsync<string>("getCookie", "XSRF-TOKEN"); //FORM HttpContent httpcontent = new StringContent($"X-CSRF-TOKEN-FORM={token}", System.Text.Encoding.UTF8); httpcontent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded"); using HttpResponseMessage responseMessage = await Http.PostAsync("WeatherForecast", httpcontent); forecasts = await JsonSerializer.DeserializeAsync<WeatherForecast[]>(await responseMessage.Content.ReadAsStreamAsync());
在Header中附加令牌
//HEADER Http.DefaultRequestHeaders.Add("X-CSRF-TOKEN-HEADER", token); forecasts = await Http.PostJsonAsync<WeatherForecast[]>("WeatherForecast", httpcontent);