I have an API which returns me a token and using that token I am able to make more requests to the API, right now I am storing the token in session however I think using session defeats the entire purpose of using a token so I am wondering how can I store the token in a cookie? Below is the code where I am getting the token and writing it to session:-
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();
}
}
This token expires after 60 mins so I have to take care of that as well and I only use this token for accessing one specific endpoint, I dont use this for authentication or authorization. What changes do I make so I can store it in cookie or maybe in localstorage?