【发布时间】:2017-05-28 22:21:22
【问题描述】:
我在服务器端使用 asp.net core,在客户端使用 xamarin。我使用 JWT 令牌,我想同时验证伪造令牌。
这是我的客户端代码:
public async Task<string> PostAsync(object model, string url)
{
var cookieContainer = new CookieContainer();
var handlerhttps = new HttpClientHandler
{
UseCookies = true,
UseDefaultCredentials = true,
CookieContainer = cookieContainer
};
var clientPage = new HttpClient(handler: handlerhttps)
{
BaseAddress = new Uri(uriString: Application.Current.Resources[index: "Domain"] + "/api/token")
};
var pageWithToken = await clientPage.GetAsync(requestUri: clientPage.BaseAddress);
var verificationToken = await pageWithToken.Content.ReadAsStringAsync();
using (var handler = new HttpClientHandler
{
CookieContainer = cookieContainer,
UseDefaultCredentials = true,
UseCookies = true
})
{
using (var client = new HttpClient(handler: handler) {BaseAddress = new Uri(uriString: url)})
{
client.DefaultRequestHeaders.Add(name: "RequestVerificationToken", value: verificationToken);
if (Application.Current.Properties[key: "Token"] != null)
{
var token = Application.Current.Properties[key: "Token"].ToString();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(scheme: "Bearer", parameter: token);
}
var json = JsonConvert.SerializeObject(value: model);
var content = new StringContent(content: json, encoding: Encoding.UTF8,
mediaType: "application/json");
var response = await client.PostAsync(requestUri: client.BaseAddress, content: content);
var result = await response.Content.ReadAsStringAsync();
return result;
}
}
}
我的问题是当我在服务器端同时使用[ValidateAntiForgeryToken] 和[Authorize] 时,我收到了 400 错误请求。
但是当我删除[ValidateAntiForgeryToken]时,它会毫无问题地授权。
当我删除 [Authorize] 时,我没有收到 400 bad request 并且它成功验证了伪造令牌。
我不知道如何解决这个问题。
【问题讨论】:
标签: xamarin asp.net-core-mvc jwt dotnet-httpclient antiforgerytoken