简体   繁体   中英

Best way of storing the jwt token in a http client class

So i have my two functions and they work which is great but how does one best store the token

public async Task<string> GenerateBarrerToken()
{
        var json = JsonConvert.SerializeObject(User);
        string token = string.Empty;
        var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
        // Do the actual request and await the response
        var httpResponse = await _client.PostAsync(Constants.ApiUrl + Constants.Authenticate, httpContent);
        if (httpResponse.StatusCode == System.Net.HttpStatusCode.OK)
        {
            var jsonContent = await httpResponse.Content.ReadAsStringAsync();
            var tok = JsonConvert.DeserializeObject<AuthenicationResponseOjbect>(jsonContent);
            token = tok.JwtToken;
        }
        return token;
}

I obv want to check to see if the token is valid here but I would need to do that with the token encrypted or something, to ensure it doesn't get tampered with.

What should I check in my get stock method that I have the valid barrer token? Is calling AddAuthenicationHeader enough on the get stock data method to keep it secure?

public async void AddAuthenicationHeader()
{
         string bearerToken = await GenerateBarrerToken();
        _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
}

public async Task<List<StockItem>> GetStockData(string BomCode, string deviceId)
{
        List<StockItem> _result = new List<StockItem>();
        var uri = new Uri(string.Format(Constants.ApiUrl + Constants.GetAllSockEndPoint, string.Empty));

        var response = await _client.GetAsync(uri);
        if (response.IsSuccessStatusCode)
        {
            var byteArray = await response.Content.ReadAsByteArrayAsync();

            var content = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
            _result = JsonConvert.DeserializeObject<List<StockItem>>(content);
        }

        return _result.ToList();
}

You should check it in GetAllStock api endpoint using [Authorize] Attribute. It will be something like this

[HttpGet]
[Authorize]
public async Task<IActionResult> GetAll(){
    ....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM