IdentityModel应用

用NuGet管理IdentityModel。

两个步骤:

1、获取Token;

2、利用Token执行HTTP请求。


代码如下:

using IdentityModel.Client;

 获取Token

        public static string GetClientToken()
        {
            string url = ConfigurationManager.AppSettings["GetClientTokenUrl"];
            HttpClient client = new HttpClient();
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
            client.BaseAddress = new Uri(url);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

            var c = client.RequestTokenAsync(new TokenRequest()
            {
                Address = url,
                ClientId = ConfigurationManager.AppSettings["ClientId"],
                ClientSecret = ConfigurationManager.AppSettings["ClientSecret"],
                GrantType = ConfigurationManager.AppSettings["GrantType"],
                Parameters =
                {
                    { "scope", ConfigurationManager.AppSettings["Method"] },
                }

            }).GetAwaiter();
            var r = c.GetResult();
            if (r.IsError) throw new Exception(r.Error);
            return r.AccessToken;
        }

把Token写入请求头,执行HTTP请求获取数据 

        public static string Post(string para)
        {
            string url = ConfigurationManager.AppSettings["SearchUrl"];
            string token = GetClientToken();
            HttpClient client = new HttpClient();
            client.SetBearerToken(token);

            StringContent content = new StringContent(para, Encoding.UTF8, "application/json");
            var finalRes = client.PostAsync(url, content).GetAwaiter().GetResult();

            return finalRes.Content.ReadAsStringAsync().GetAwaiter().GetResult();
        }

查询接口参数Json

string para = "{\"type\":\"\",\"isReleased\":\"true\",\"allSite\":false,\"pageSize\":0}";

猜你喜欢

转载自blog.csdn.net/u012835032/article/details/105432371