這裏以Asp.net Core的服務端而且Asp.net Core託管客戶端爲例,跨域請求的參考其餘跨域設置。javascript
在Asp.net Core中,XSRF/CSRF是經過驗證http頭或form表單中的字段來驗證請求的。java
在Asp.net Core的Startup中注入以下服務以啓用防止跨站點請求僞造 (XSRF/CSRF) 攻擊git
services.AddAntiforgery(options =>{ options.HeaderName = "X-CSRF-TOKEN-HEADER"; options.FormFieldName = "X-CSRF-TOKEN-FORM"; });
啓用以下中間件以在Cookie中寫入令牌github
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讀取Cookieajax
@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中附加令牌app
//HEADER Http.DefaultRequestHeaders.Add("X-CSRF-TOKEN-HEADER", token); forecasts = await Http.PostJsonAsync<WeatherForecast[]>("WeatherForecast", httpcontent);