存储令牌而无需重新生成每个请求-Web API

时间:2019-01-30 08:27:44

标签: c# asp.net-core access-token

我有API 1API 2

API 2需要令牌,我将从Identity获取令牌并将其发送到API 2

但是现在的问题是,我不知道将令牌存储在API 1中的位置。因此,临时解决方案是,每次将请求发送到API 2时,我都会不断请求令牌。

令牌获得了过期时间,如果已经过期,则生成新令牌

可以做到吗?

我的代码段

  var pairs = new List < KeyValuePair < string,
  string >> {
   new KeyValuePair < string,
   string > ("client_id", "spa"),
   new KeyValuePair < string,
   string > ("client_secret", "secretkey"),
   new KeyValuePair < string,
   string > ("grant_type", "password"),
   new KeyValuePair < string,
   string > ("username", "test@test"),
   new KeyValuePair < string,
   string > ("Password", "test1234")


  };
 var content = new FormUrlEncodedContent(pairs);

 using(var client = new HttpClient()) {
  var response = client.PostAsync("https://myidentity.com/" + "connect/token", content).Result;
  var result = response.Content.ReadAsStringAsync().Result;

  var t = JsonConvert.DeserializeObject < Token > (result);

  //Sent request to API 2
 }

我的令牌类

public class Token
{
    public string access_token { get; set; }
    public string token_type { get; set; }
    public int expires_in { get; set; }
    public string userName { get; set; }
    [JsonProperty(".issued")]
    public string issued { get; set; }
    [JsonProperty(".expires")]
    public string expires { get; set; }
}

0 个答案:

没有答案