统一身份认证服务|统一身份认证服务 源码(客户端)

/// /// 参考说明:http请求统一身份认证服务 /// /// 服务地址,服务地址参考统一身份认证服务API页面 /// HTTP 请求方法 /// HTTP POST 请求时,传入对象参数 /// 远程统一认证服务响应消息 private string HttpRequest(string address, EnumHttpMethod method, string paramObj) { using (WebClient httpClient = new WebClient()) { //步骤1:设置统一身份认证服务的服务地址 httpClient.BaseAddress = IOVAuthrizeBaseUri; //步骤2:HTTP 请求的标头中需要添加“Authorization”,参考如下: httpClient.Headers.Add("Content-Type", "application/json"); httpClient.Headers.Add("Authorization", GetAuthorization(AppID, AppSecret)); try { //步骤3:请求远程资源 string response = string.Empty; if (method == EnumHttpMethod.POST) { //序列化对象参数 var jsonObj = JsonConvert.SerializeObject(paramObj); //编码 byte[] postData = https://www.it610.com/article/Encoding.UTF8.GetBytes(jsonObj); //POST请求 byte[] responseData = httpClient.UploadData(address,"POST", postData); // 得到返回字符流 response = Encoding.UTF8.GetString(responseData); // 解码 } else { //特别说明:address 在GET请求形势下,如果有参数address示例:api/Token/Refresh?accessToken={accessToken} byte[] responseData = https://www.it610.com/article/httpClient.DownloadData(address); // 得到返回字符流 response = Encoding.UTF8.GetString(responseData); // 解码 } return response; } catch (WebException ex) { //获取统一认证服务返回的信息 var res = (HttpWebResponse)ex.Response; //HTTP状态401:身份认证不通过 if (res.StatusCode == HttpStatusCode.Unauthorized) { //未授权,尝试检查步骤2。错误原因(1):未添加“Authorization”;错误原因(2):应用ID或应用秘钥不正确。 return string.Empty; } else { //获取详细的错误信息,这时可能统一身份认证服务出现内部异常或者客户端出现内部异常,可使用 //下面代码抛出异常明细 StreamReader sr = new StreamReader(res.GetResponseStream()); var strHtml = sr.ReadToEnd(); throw new Exception(strHtml); } } } } /// /// 获取Authorization标头值 /// /// 【统一身份认证服务|统一身份认证服务 源码(客户端)】统一认证服务颁发的应用ID /// 统一认证服务颁发的应用秘钥 /// 标头值 private string GetAuthorization(string appID, string appSecret) { var authorization = string.Format("{0}:{1}", appID, appSecret); return "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(authorization)); } /// /// HTTP 请求方法 /// public enum EnumHttpMethod { POST, GET }


转载于:https://www.cnblogs.com/fjzhang/p/7908140.html

    推荐阅读