HttpWebRequest 请求带OAuth2 授权的webapi
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的更多相关文章
- 基于OWIN ASP.NET WebAPI 使用OAUTH2授权服务的几点优化
前面在ASP.NET WEBAPI中集成了Client Credentials Grant与Resource Owner Password Credentials Grant两种OAUTH2模式,今天 ...
- Spring Security 实战干货:客户端OAuth2授权请求的入口
1. 前言 在Spring Security 实战干货:OAuth2第三方授权初体验一文中我先对OAuth2.0涉及的一些常用概念进行介绍,然后直接通过一个DEMO来让大家切身感受了OAuth2.0第 ...
- Spring Security 实战干货:OAuth2授权请求是如何构建并执行的
在Spring Security 实战干货:客户端OAuth2授权请求的入口中我们找到了拦截OAuth2授权请求入口/oauth2/authorization的过滤器OAuth2Authorizati ...
- 隔离这几天开发了一个带控制台的OAuth2授权服务器分享给大家
停更这些天,业余时间和粉丝群的几个大佬合作写了一个基于Spring Authorization Server的OAuth2授权服务器的管理控制台项目Id Server,我觉得这个项目能够大大降低OAu ...
- 通过Dapr实现一个简单的基于.net的微服务电商系统(九)——一步一步教你如何撸Dapr之OAuth2授权
Oauth2授权,熟悉微信开发的同学对这个东西应该不陌生吧.当我们的应用系统需要集成第三方授权时一般都会做oauth集成,今天就来看看在Dapr的语境下我们如何仅通过配置无需修改应用程序的方式让第三方 ...
- C# winfrom HttpWebRequest 请求获取html网页信息和提交信息
string result =GetRequest("http://localhost:32163/DuoBao/ajax.aspx", "time=5"); ...
- 通过HttpWebRequest请求https接口
一.为什么进行代理接口的开发: 有些项目需要访问被墙了哒网站,比如前不久公司开发项目需要使用google地图的接口,而google在中国被墙了,所有打算做一个代理接口服务,将代理放到国外服务器上,通过 ...
- [认证授权] 2.OAuth2授权(续) & JWT(JSON Web Token)
1 RFC6749还有哪些可以完善的? 1.1 撤销Token 在上篇[认证授权] 1.OAuth2授权中介绍到了OAuth2可以帮我们解决第三方Client访问受保护资源的问题,但是只提供了如何获得 ...
- WebApi实现验证授权Token,WebApi生成文档等 - CSDN博客
原文:WebApi实现验证授权Token,WebApi生成文档等 - CSDN博客 using System; using System.Linq; using System.Web; using S ...
随机推荐
- 【Android基础】利用Intent在Activity之间传递数据
前言: 上一篇文章给大家聊了Intent的用法,如何用Intent启动Activity和隐式Intent,这一篇文章给大家聊聊如何利用Intent在Activity之间进行沟通. 从一个Activ ...
- 剑指offer--2
前言:继续笔记分享! 面试题6:暂无好的解决方法先搁浅一下 面试题7: #include<stdio.h> #include<stdlib.h> typedef struct ...
- [Web安全之实战] 跨站脚本攻击XSS
Writer:BYSocket(泥沙砖瓦浆木匠) 微博:BYSocket 豆瓣:BYSocket Reprint it anywhere u want. 文章Points: 1. 认识XSS 2. ...
- ①泡茶看数据结构-表ADT
前言 小朽,晚上回到寝室.烧了开水,又泡了一杯下午喝了的小毛尖.耳机听着萨克斯,总结下今天学的数据结构和算法中的表ADT. 表ADT节点: #单链表 #双链表 #循环链表 ...
- 搭建私有CA服务器
1 CA是什么 CA(Certificate Authority)证书颁发机构主要负责证书的颁发.管理以及归档和吊销.证书内包含了拥有证书者的姓名.地址.电子邮件帐号.公钥.证书有效期.发放证书的CA ...
- Go语言的map如何判断key是否存在
判断方式为value,ok := map[key], ok为true则存在 package main import "fmt" func main() { demo := map[ ...
- Mysql加锁过程详解(1)-基本知识
Mysql加锁过程详解(1)-基本知识 Mysql加锁过程详解(2)-关于mysql 幻读理解 Mysql加锁过程详解(3)-关于mysql 幻读理解 Mysql加锁过程详解(4)-select fo ...
- 巨杉数据库 MySQL兼容项目正式开源
9月7日.8日,2018 ODF 开源数据库论坛,在北京盛大开幕.在大会上,巨杉数据库正式发布了巨杉全新的MySQL/MariaDB兼容架构,并将项目正式开源. 开源数据库论坛(ODF)是中国开源数 ...
- [转]GitLab Continuous Integration (GitLab CI/CD)
本文转自:https://docs.gitlab.com/ee/ci/README.html GitLab Continuous Integration (GitLab CI/CD) The bene ...
- .Net EF6+Mysql 环境搭建
由于一直使用的数据库是mysql,之前所用的orm都是轻量级的例如 dapper 这些的,然后想用ef配置一下mysql,总共时间花了差不多2天,才将坑填完,写个博客将流程记录一下 给后来者少掉点坑. ...