# Vite使用Axios傳CSRF token 出現CORS ERROR(更新解決方案) :::success https://ithelp.ithome.com.tw/questions/10212740?sc=rss.qu header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: *'); header('Access-Control-Allow-Headers: *'); ::: :::info It's a known issue after Axios 1.6.0. You have to modify your axios configuration and set withXSRFToken to true, as below: axios.defaults.withCredentials = true; axios.defaults.withXSRFToken = true; ::: # HTML5 安全性備忘單 HTML5 Security Cheatsheet https://html5sec.org/ https://vuejs.org/guide/best-practices/security # ASP.NET Core 的内置防伪造服务来生成令牌。 在 Startup.cs 中配置防伪造服务: ~~~ 1.產生 CSRF 令牌: * 假設你的應用程式使用基於 Cookie 的身份驗證,你可以在伺服器端產生 CSRF 令牌並將其儲存在使用者會話中。 * 你可以使用 ASP.NET Core 的內建防偽造服務來產生令牌。在 Startup.cs 中配置防偽造服務: public void ConfigureServices(IServiceCollection services) { // ... services.AddAntiforgery(options => options.HeaderName = "X-CSRF-TOKEN"); builder.Services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN"); // ... } https://github.com/dotnet/AspNetCore.Docs/blob/main/aspnetcore/security/anti-request-forgery/samples/2.x/MvcSample/Startup.cs https://github.com/dotnet/AspNetCore.Docs/blob/main/aspnetcore/security/anti-request-forgery/samples/6.x/AntiRequestForgerySample/Program.cs https://github.com/dotnet/AspNetCore.Docs/blob/main/aspnetcore/security/anti-request-forgery/samples/7.x/AntiRequestForgeryMinimalSample/Program.cs https://www.796t.com/content/1545906821.html 2. 在前端取得 CSRF 令牌: mounted() { this.csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content'); } 然後,在每個請求中包含這個令牌。使用 Axios 或其他網路請求庫傳送請求時, 將令牌作為請求標頭或請求主體的一部分傳遞。例如: methods: { async submitForm() { try { await axios.post('/api/submit', { token: this.csrfToken, // 其他请求数据 }); // 请求成功后的处理 } catch (error) { // 请求失败后的处理 } }, } 3 在伺服器端驗證 CSRF 令牌: 最後,伺服器端需要驗證 CSRF 令牌的有效性。 可以透過比較請求中的令牌和使用者會話中儲存的令牌來進行驗證。 如果令牌匹配,則處理請求;如果令牌不匹配,則傳回錯誤回應。 ~~~