我正在尝试使用 VS2019 (C#) 和 RestSharp 通过 API 调用测试 Anti Forgery 令牌。我正在做的是对我们的登录页面执行 GET 以获取 4 个令牌/cookie,然后使用用户名和密码将这些附加到 POST 以尝试登录。第一次调用成功并返回给我一个 HTTP 200 和 4 个 cookie/令牌(ASP.NET_SessionId、XSRF-TOKEN、XSRF-COOKIE 和一个 __RequestVerificationToken - 都作为 cookie(在 cookiecontainer 中)附加到 POST API 调用),然而,第二次调用失败并显示 HTTP 500 并显示以下消息:“验证提供的防伪令牌失败。cookie“__RequestVerificationToken”和表单字段“__RequestVerificationToken”已交换。”。我在我的 POST 调用中包含此令牌两次 - 一次作为 cookie,一次作为请求正文的一部分。
谢谢,
杰米。
public void LogIn(string userName, string password)
{
// 1st call to get the cookies and tokens.
CommonProperties.Client = new RestClient { CookieContainer = new CookieContainer() };
CommonProperties.Client.BaseUrl = new Uri($"https://localhost:50000/Account/Login");
var request = new RestRequest(Method.GET);
request.AddParameter("ReturnUrl", "%2F", ParameterType.QueryString);
CommonProperties.Response = CommonProperties.Client.Execute(request);
CommonProperties.Client.BaseUrl = new Uri($"https://localhost:50000/Account/Login");
var requestToken = CommonProperties.Response.Cookies.Single(c => c.Name ==
"__RequestVerificationToken");
// 2nd call to log in.
request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Accept-Encoding", "gzip, deflate, br");
request.AddHeader("Accept", "*/*");
request.AddHeader("Referer", $"https://localhost:50000/Account/Login");
request.AddParameter("undefined", $"__RequestVerificationToken=
{requestToken.Value}&UserName=userName&Password=password_321", ParameterType.RequestBody);
CommonProperties.Response = CommonProperties.Client.Execute(request);
}