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

  private static string GetAuthorization(string username, string password)
{
string authorization = string.Format("{0}:{1}", username, password); return "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(authorization));
}
   /// <summary>
/// 获取Token
/// </summary>
/// <returns></returns>
private static string OAuthClientCredentialsToken()
{
const string clientId = "";
const string clientSecret = "";
string result = string.Empty; HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(_baseUrl + "/token");
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Accept = "application/json";
httpWebRequest.Timeout = ;
httpWebRequest.KeepAlive = false;
httpWebRequest.AllowAutoRedirect = true;
// httpWebRequest.Headers.Add("Accept-Language", "zh-cn");
// httpWebRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
// httpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.1.4322)";
httpWebRequest.Headers.Add("Authorization", GetAuthorization(clientId, clientSecret));
//Credentials
httpWebRequest.Credentials = CredentialCache.DefaultCredentials;
//post参数
StringBuilder postParam = new StringBuilder();
Dictionary<string, string> parameters = new Dictionary<string, string> { { "grant_type", "client_credentials" } };
int i = ;
foreach (KeyValuePair<string, string> parameter in parameters)
{
if (i > )
postParam.Append("&");
postParam.AppendFormat("{0}={1}", parameter.Key, HttpUtility.UrlEncode(parameter.Value));
i++;
} byte[] postData = Encoding.UTF8.GetBytes(postParam.ToString());
httpWebRequest.ContentLength = postData.Length; try
{
Stream requesStream = httpWebRequest.GetRequestStream();
requesStream.Write(postData, , postData.Length);
requesStream.Close(); WebResponse response = httpWebRequest.GetResponse();
Stream stream = response.GetResponseStream();
if (stream != null)
{
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
reader.Close();
}
stream.Close();
}
}
catch (WebException ex)
{
throw new Exception(ex.Message);
}
return !string.IsNullOrWhiteSpace(result) ? JObject.Parse(result)["access_token"].Value<string>() : result;
}

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

  /// <summary>
/// HttpGet
/// </summary>
/// <param name="url"></param>
/// <param name="token"></param>
/// <param name="contentType"></param>
/// <returns></returns>
private static string HttpGet(string url, string token, string contentType = "application/x-www-form-urlencoded")
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "GET";
httpWebRequest.ContentType = contentType;
httpWebRequest.Accept = "application/json";
httpWebRequest.Timeout = ;
httpWebRequest.AllowAutoRedirect = false;
//Bearer+空格
httpWebRequest.Headers.Add("Authorization", "Bearer " + token);
httpWebRequest.Credentials = CredentialCache.DefaultCredentials; string result = null;
try
{
WebResponse response = httpWebRequest.GetResponse();
Stream responseStream = response.GetResponseStream();
if (responseStream != null)
{
using (StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8))
{
result = streamReader.ReadToEnd();
streamReader.Close();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return result;
}

HttpWebRequest 请求带OAuth2 授权的webapi的更多相关文章

  1. 基于OWIN ASP.NET WebAPI 使用OAUTH2授权服务的几点优化

    前面在ASP.NET WEBAPI中集成了Client Credentials Grant与Resource Owner Password Credentials Grant两种OAUTH2模式,今天 ...

  2. Spring Security 实战干货:客户端OAuth2授权请求的入口

    1. 前言 在Spring Security 实战干货:OAuth2第三方授权初体验一文中我先对OAuth2.0涉及的一些常用概念进行介绍,然后直接通过一个DEMO来让大家切身感受了OAuth2.0第 ...

  3. Spring Security 实战干货:OAuth2授权请求是如何构建并执行的

    在Spring Security 实战干货:客户端OAuth2授权请求的入口中我们找到了拦截OAuth2授权请求入口/oauth2/authorization的过滤器OAuth2Authorizati ...

  4. 隔离这几天开发了一个带控制台的OAuth2授权服务器分享给大家

    停更这些天,业余时间和粉丝群的几个大佬合作写了一个基于Spring Authorization Server的OAuth2授权服务器的管理控制台项目Id Server,我觉得这个项目能够大大降低OAu ...

  5. 通过Dapr实现一个简单的基于.net的微服务电商系统(九)——一步一步教你如何撸Dapr之OAuth2授权

    Oauth2授权,熟悉微信开发的同学对这个东西应该不陌生吧.当我们的应用系统需要集成第三方授权时一般都会做oauth集成,今天就来看看在Dapr的语境下我们如何仅通过配置无需修改应用程序的方式让第三方 ...

  6. C# winfrom HttpWebRequest 请求获取html网页信息和提交信息

    string result =GetRequest("http://localhost:32163/DuoBao/ajax.aspx", "time=5"); ...

  7. 通过HttpWebRequest请求https接口

    一.为什么进行代理接口的开发: 有些项目需要访问被墙了哒网站,比如前不久公司开发项目需要使用google地图的接口,而google在中国被墙了,所有打算做一个代理接口服务,将代理放到国外服务器上,通过 ...

  8. [认证授权] 2.OAuth2授权(续) & JWT(JSON Web Token)

    1 RFC6749还有哪些可以完善的? 1.1 撤销Token 在上篇[认证授权] 1.OAuth2授权中介绍到了OAuth2可以帮我们解决第三方Client访问受保护资源的问题,但是只提供了如何获得 ...

  9. WebApi实现验证授权Token,WebApi生成文档等 - CSDN博客

    原文:WebApi实现验证授权Token,WebApi生成文档等 - CSDN博客 using System; using System.Linq; using System.Web; using S ...

随机推荐

  1. php(curl请求)测试接口案例

    请求测试接口,如下: $data = [']; $result = curlrequest($apiUrl,$data); ){ echo json_encode($result); }else{ e ...

  2. 微服务架构下分布式事务解决方案——阿里GTS

    1 微服务的发展 微服务倡导将复杂的单体应用拆分为若干个功能简单.松耦合的服务,这样可以降低开发难度.增强扩展性.便于敏捷开发.当前被越来越多的开发者推崇,很多互联网行业巨头.开源社区等都开始了微服务 ...

  3. 【Python】正则表达式纯代码极简教程

    <Python3正则表达式>文字版详细教程链接:https://www.cnblogs.com/leejack/p/9189796.html ''' 内容:Python3正则表达式 日期: ...

  4. 敏感词汇过滤DFA算法

    using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Tex ...

  5. Perl面向对象(2):对象

    本系列: Perl面向对象(1):从代码复用开始 Perl面向对象(2):对象 Perl面向对象(3):解构--对象销毁 第3篇依赖于第2篇,第2篇依赖于1篇. 已有的代码结构 现在有父类Animal ...

  6. 翻译:select into outfile(已提交到MariaDB官方手册)

    本文为mariadb官方手册:SELECT INTO OUTFILE的译文. 原文:https://mariadb.com/kb/en/select-into-outfile/ 我提交到MariaDB ...

  7. centos7修改网卡名称为eth0-技术流ken

    前言 在配置集群的时候,需要保持网卡名称一致,所以我们需要修改centos7中的网卡名称为eth0. 检查网卡 检查网卡,现在网卡名称是ens33 [root@localhost ~]# ip a : ...

  8. C# 隐式转换关键字 implicit

    implicit 关键字用于声明隐式的用户定义类型转换运算符. 如果可以确保转换过程不会造成数据丢失,则可使用该关键字在用户定义类型和其他类型之间进行隐式转换. 引用摘自:implicit(C# 参考 ...

  9. [转]GitLab Continuous Integration (GitLab CI/CD)

    本文转自:https://docs.gitlab.com/ee/ci/README.html GitLab Continuous Integration (GitLab CI/CD) The bene ...

  10. 【转载】ASP.NET MVC设置允许跨域访问

    默认情况下,浏览器端发送Ajax请求一般被禁止跨域访问,如A域名网站访问B域名网站的请求会被终止,在ASP.NET MVC项目中,我们可以配置相应的设置项,允许网站的接口跨域访问,主要需要设置Acce ...