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. ⑦JSP2.0的福利(标签文件)

    前言 本篇接着上一篇博客:[传送门] 这次讲的是JSP2.0的特性之一,我们可以编写标签文件,指没有标签处理器和标签类库描述符的定制动作指令,不编译,无标签类描述符. 本文结构: ①标签文件简介 ②第 ...

  2. Chapter 4 Invitations——4

    I wanted very much to talk to him, and the day after the accident I tried. 在发生事故之后我尽力尝试,我很想和他聊聊. The ...

  3. 1197多行事务要求更大的max_binlog_cache_size处理与优化

    1197多语句事务要求更大的max_binlog_cache_size报错   binlog_cache_size:为每个session 分配的内存,在事务过程中用来存储二进制日志的缓存,提高记录bi ...

  4. Gradle nexus 解决开发机器不连网无法下载gradle插件问题

    在用gradle时常规配置如下(D:\gradle-4.9\init.d\init.gradle文件,没有这个文件时自建): ext { nexus = 'http://192.168.127.128 ...

  5. 动态代理实现AOP

    代理 代理顾名思义:代为处理.不是对目标对象的直接操作,而是通过代理对目标对象进行包装,此时可以在目标对象的基础上添加额外的操作以满足业务需求.图示 分类:动态代理.静态代理. 代理三要素:共同接口. ...

  6. npm设置和查看仓库源

    转载请注明出处:https://www.cnblogs.com/wenjunwei/p/10078460.html 在使用npm命令时,如果直接从国外的仓库下载依赖,下载速度很慢,甚至会下载不下来,我 ...

  7. MySQL中间件之ProxySQL(11):链式规则( flagIN 和 flagOUT )

    返回ProxySQL系列文章:http://www.cnblogs.com/f-ck-need-u/p/7586194.html 1.理解链式规则 在mysql_query_rules表中,有两个特殊 ...

  8. Perl包相关

    名称冲突问题 假如在sum2.pm中使用require导入了一个代码文件sum1.pm: #!/usr/bin/env perl use strict; use warnings; use 5.010 ...

  9. 解读经典《C#高级编程》第七版 Page50-68.核心C#.Chapter2

    前言 本篇讲述Main方法,控制台,注释,预处理指令,编程规范等.这些概念比较琐碎,为避免长篇大论,主要以列举要点的方式来说明. 01 Main方法 Main方法并不是所有应用类型的入口方法,它只是控 ...

  10. Linux中安装Oracle11g后出现监听的问题及解决办法

    软件安装: 参考文章: linux安装Oracle11G 错误如下: [oracle@iz2f570bi1k56uz admin]$ lsnrctl start LSNRCTL for Linux: ...