HttpWebRequest 请求带OAuth2 授权的webapi

时间:2022-12-19 21:29:15

OAuth 2.0注意事项
1、 获取access_token时,请使用POST

HttpWebRequest  请求带OAuth2 授权的webapiHttpWebRequest  请求带OAuth2 授权的webapi
1  private static string GetAuthorization(string username, string password)
2 {
3 string authorization = string.Format("{0}:{1}", username, password);
4
5 return "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(authorization));
6 }
View Code
HttpWebRequest  请求带OAuth2 授权的webapiHttpWebRequest  请求带OAuth2 授权的webapi
 1   /// <summary>
2 /// 获取Token
3 /// </summary>
4 /// <returns></returns>
5 private static string OAuthClientCredentialsToken()
6 {
7 const string clientId = "8518";
8 const string clientSecret = "8518";
9 string result = string.Empty;
10
11 HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(_baseUrl + "/token");
12 httpWebRequest.Method = "POST";
13 httpWebRequest.ContentType = "application/x-www-form-urlencoded";
14 httpWebRequest.Accept = "application/json";
15 httpWebRequest.Timeout = 15000;
16 httpWebRequest.KeepAlive = false;
17 httpWebRequest.AllowAutoRedirect = true;
18 // httpWebRequest.Headers.Add("Accept-Language", "zh-cn");
19 // httpWebRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
20 // httpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.1.4322)";
21 httpWebRequest.Headers.Add("Authorization", GetAuthorization(clientId, clientSecret));
22 //Credentials
23 httpWebRequest.Credentials = CredentialCache.DefaultCredentials;
24 //post参数
25 StringBuilder postParam = new StringBuilder();
26 Dictionary<string, string> parameters = new Dictionary<string, string> { { "grant_type", "client_credentials" } };
27 int i = 0;
28 foreach (KeyValuePair<string, string> parameter in parameters)
29 {
30 if (i > 0)
31 postParam.Append("&");
32 postParam.AppendFormat("{0}={1}", parameter.Key, HttpUtility.UrlEncode(parameter.Value));
33 i++;
34 }
35
36 byte[] postData = Encoding.UTF8.GetBytes(postParam.ToString());
37 httpWebRequest.ContentLength = postData.Length;
38
39 try
40 {
41 Stream requesStream = httpWebRequest.GetRequestStream();
42 requesStream.Write(postData, 0, postData.Length);
43 requesStream.Close();
44
45 WebResponse response = httpWebRequest.GetResponse();
46 Stream stream = response.GetResponseStream();
47 if (stream != null)
48 {
49 using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
50 {
51 result = reader.ReadToEnd();
52 reader.Close();
53 }
54 stream.Close();
55 }
56 }
57 catch (WebException ex)
58 {
59 throw new Exception(ex.Message);
60 }
61 return !string.IsNullOrWhiteSpace(result) ? JObject.Parse(result)["access_token"].Value<string>() : result;
62 }
View Code

 

2、 访问需要授权的Api,请使用http/https协议,并且加上access token的Header
3 、Header格式为"Authorization: Bearer access_token",其中Bearer后面有一个空格

HttpWebRequest  请求带OAuth2 授权的webapiHttpWebRequest  请求带OAuth2 授权的webapi
 1  /// <summary>
2 /// HttpGet
3 /// </summary>
4 /// <param name="url"></param>
5 /// <param name="token"></param>
6 /// <param name="contentType"></param>
7 /// <returns></returns>
8 private static string HttpGet(string url, string token, string contentType = "application/x-www-form-urlencoded")
9 {
10 HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
11 httpWebRequest.Method = "GET";
12 httpWebRequest.ContentType = contentType;
13 httpWebRequest.Accept = "application/json";
14 httpWebRequest.Timeout = 15000;
15 httpWebRequest.AllowAutoRedirect = false;
16 //Bearer+空格
17 httpWebRequest.Headers.Add("Authorization", "Bearer " + token);
18 httpWebRequest.Credentials = CredentialCache.DefaultCredentials;
19
20 string result = null;
21 try
22 {
23 WebResponse response = httpWebRequest.GetResponse();
24 Stream responseStream = response.GetResponseStream();
25 if (responseStream != null)
26 {
27 using (StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8))
28 {
29 result = streamReader.ReadToEnd();
30 streamReader.Close();
31 }
32 }
33 }
34 catch (Exception ex)
35 {
36 throw new Exception(ex.Message);
37 }
38 return result;
39 }
View Code