在无状态 ASP.NET Core 8 Web API 中实现 CSRF 令牌,无需 Views/MVC!

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。

之所以要写这篇文章,是因为找不到其他好的教程。看到的搜索结果全是关于服务器端渲染视图的。所以花了数个小时在网上搜索,学习了 CSRF 令牌、cookie 以及所有相关的知识。最终,对这个主题有了相当全面的了解。

后端环境基于.NET,前端环境则是一个客户端渲染项目。
以下是详细搭建步骤。

首先,对 Program.cs 文件进行了修改:

using Microsoft.AspNetCore.Antiforgery;

builder.Services.AddAntiforgery(options =>

{

options.Cookie = new CookieBuilder {

HttpOnly = true, // for security purposes, this means that when csrf endpoint responses with "set-cookie" header then the cookie is httpOnly which means the cookie is stored to the browser, BUT webpage's javascript can't access it.

Domain = "your-site-url-here.com",

Expiration = new TimeSpan(TimeSpan.TicksPerMinute),

Path = "/", // I had to put it to just a slash, otherwise the set-cookie would work for me. Maybe some configuration can fix other paths.

Name = "csrf"

// SameSite = SameSiteMode.None, // for localhost I had to use SameSite.None, but in test server it broke things for me.

// SecurePolicy = CookieSecurePolicy.Always // for localhost I had to use it according to Chrome's dev tool network tab for the set-cookie to apply to cookies. But did not need it in test server.

},

options.HeaderName = "X-CSRF-TOKEN"; // This name is also important, because the same name must be present in your request's headers from frontend

options.SuppressXFrameOptionsHeader = false; // For Clickjacking

});

builder.Services.AddControllersWithViews(options => {

// Only AddControllersWithViews works, "AddControllers" is not enough here.

options.Filters.Add(new Microsoft.AspNetCore.Mvc.ValidateAntiForgeryTokenAttribute());

// Adds CSRF token validation to all controllers and their actions

});

// after var app = builder.Build();

app.UseAntiforgery();

然后添加了一个用于获取 CSRF 令牌的控制器:

using Microsoft.AspNetCore.Antiforgery;

using Microsoft.AspNetCore.Authorization;

using Microsoft.AspNetCore.Mvc;

namespace Your.Controllers;

ApiController

Route("api/csrf")

public class CsrfController(IAntiforgery antiforgery) {

HttpGet("")

AllowAnonymous

IgnoreAntiforgeryToken

// So the CSRF token validation is turned off for this action because you have to get an acces to this endpoint always for a token.

public IActionResult GetCsrf() {

var tokenSet = antiforgery.GetAndStoreTokens(HttpContext); // This generates the tokens for your cookies and requests and adds needed response headers for your browser.

// The response contains the request token as in "Ok" method and if you look in browser response headers then there is "set-cookie" named header which contains cookie token which is automatically set to your browsers cookies which are inaccessible for javascript but the csrf cookie is sent automatically with the next request you make from frontend.

return Ok(tokenSet.RequestToken);

}

}

最后,预先从前端对所有 API 请求应用了 CSRF 令牌获取机制:

const getCsrfToken = async () => {

return fetch(`${APIURL}/api/csrf`)

.then(data => data.json())

.catch(error => console.error("Error fetchin CSRF token: ", error))

}

const apiFetch = async (url, params..., and so on) => {

const csrfResult = await getCsrfToken();

// in your fetch add "X-CSRF-TOKEN" to headers with value <csrfResult> (or request_token, depending on your casing settings in backend)

}

希望这篇文章对大家有所帮助。如果发现任何错误,请随时留言指正。

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。

相关推荐
溪语流沙4 分钟前
【Web全栈进阶】Vue3起步:组件、模板语法、响应式数据
前端·javascript·vue.js·css3
众链网络5 分钟前
Agent 重试的工程解法:幂等、断点续跑与熔断怎么落地
java·前端·数据库·人工智能
User_芊芊君子23 分钟前
JiuwenSwarm 协同智能体落地金融投研全流程:SwarmFlow 工作流编排与人机交互面板实测(A2UI v0.8 Web 通道适配)
前端·金融·人机交互
程序员大阳1 小时前
副队长CSS教程(37)–transition 过渡
前端·css·transition·过渡
ZoeLandia1 小时前
TypeScript 01:类型注解与类型推断
前端·javascript·typescript
踩蚂蚁1 小时前
从“打开灯光”看 KWS 多关键词语音控制是怎么工作的
前端
ppiero1 小时前
AI 助手聊着聊着就失忆?先分清"上下文"和"记忆"(五步装长期记忆)
前端
打呵欠的猫1 小时前
用 AI 做性能分析:一行命令找出拖慢页面的 5 个组件,优化后首屏快了 40%
前端·性能优化·ai编程
用户5080070546281 小时前
芯飞云用了两个月,说说我的真实感受
前端
Amos_Web1 小时前
Rspack 源码解析(二十一):Cacheable 与 Storage 如何持久化编译结果
前端·rust·前端框架