【发布时间】:2020-07-04 04:03:48
【问题描述】:
我有一个 API,它返回一个令牌并使用该令牌我可以向 API 发出更多请求,现在我将令牌存储在会话中,但是我认为使用会话会破坏使用令牌的全部目的,所以我想知道如何将令牌存储在 cookie 中?下面是我获取令牌并将其写入会话的代码:-
public async Task<string> GetToken(bool tokenExpired)
{
if (_context.HttpContext.Session.GetString("token") != null && tokenExpired == false)
{
return _context.HttpContext.Session.GetString("token");
}
var authClient = _httpClientFactory.CreateClient("Auth");
var dict = new Dictionary<string, string>
{
{ "grant_type", "client_credentials" },
{ "client_id", "my_client_id" },
{ "client_secret", "my_client_secret" }
};
var res = await authClient.PostAsync(authClient.BaseAddress, new FormUrlEncodedContent(dict));
if (res.StatusCode == HttpStatusCode.OK)
{
var authentication = JsonConvert.DeserializeObject<Authentication>(res.Content.ReadAsStringAsync().Result);
_context.HttpContext.Session.SetString("token", authentication.Access_Token);
return authentication.Access_Token;
}
else
{
throw new Exception();
}
}
这个令牌在 60 分钟后过期,所以我也必须处理好这个问题,我只使用这个令牌来访问一个特定的端点,我不使用它来进行身份验证或授权。我做了哪些更改才能将其存储在 cookie 或本地存储中?
【问题讨论】:
-
根据您的代码和描述,您似乎想检查客户端是否已获取令牌以及令牌是否已过期,对于这种情况,如您所述,您可以存储它在 cookie 或本地存储等中。要将其存储在 cookie 中,您可以尝试像这样的代码
HttpContext.Response.Cookies.Append("token", authentication.Access_Token, new Microsoft.AspNetCore.Http.CookieOptions { Expires = DateTime.Now.AddMinutes(expires_in) });。 -
@FeiHan 谢谢你,如果添加这个作为答案,我会接受它
标签: .net authentication asp.net-core jwt