How to store token in cookie?

Viewed 1323

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?

1 Answers

What changes do I make so I can store it in cookie or maybe in localstorage?

As we discussed in comments, to store a acquired token in cookie, you can use following code snippet:

HttpContext.Response.Cookies.Append("token", authentication.Access_Token, 
    new Microsoft.AspNetCore.Http.CookieOptions { Expires = DateTime.Now.AddMinutes(expires_in) });

Then you can check if the client has acquired a token and if that existing token is expired in your code logic, like below.

var token = "";

if (HttpContext.Request.Cookies.TryGetValue("token",out token) && tokenExpired == false)
{
    return token;
}
return token;
//...
//code logic here
Related