【问题标题】:Best way of storing the jwt token in a http client class将 jwt 令牌存储在 http 客户端类中的最佳方式
【发布时间】:2021-02-27 16:48:02
【问题描述】:

所以我有我的两个功能,它们很好用,但是如何最好地存储令牌

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;
}

我想检查令牌在此处是否有效,但我需要对令牌进行加密或其他操作,以确保它不会被篡改。

我应该在我的 get stock 方法中检查我是否拥有有效的 barrer 令牌?在获取库存数据方法上调用 AddAuthenicationHeader 是否足以保证其安全?

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();
}

【问题讨论】:

  • 某人应该如何篡改您的令牌?它是经过签名的,只有给你令牌的机构才应该有私钥。

标签: c# asp.net jwt asp.net-web-api2


【解决方案1】:

您应该使用 [Authorize] 属性在 GetAllStock api 端点中检查它。会是这样的

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

【讨论】:

    猜你喜欢
    • 2020-12-21
    • 2021-09-20
    • 2017-12-10
    • 2021-11-16
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多