OAuth2认证和授权:ResourceOwnerPassword认证
ResourceOwnerPassword在 ClientCredentials认证上新增了用户名和密码
但通过RequestPasswordTokenAsync获取不到refresh_token,不知道为什么
using IdentityModel;
using IdentityModel.Client;
using Newtonsoft.Json.Linq;
using System;
using System.Net.Http;
using System.Text; namespace PassWord
{
/// <summary>
/// 客户端模式,请求授权服务器获取token,请求资源服务器获取资源
/// 依赖包:IdentityModel
/// </summary>
class Program
{
static void Main(string[] args)
{
string Authority = "http://localhost:5003";
string ApiResurce = "http://localhost:5002/";
var tokenCliet = new HttpClient()
{
BaseAddress = new Uri(ApiResurce)
}; /*
这样做的目的是:
资源服务器会去授权服务器认证,所以在客户端可以先判断下授权服务器是否挂了
*/
DiscoveryCache _cache = new DiscoveryCache(Authority);
var disco1 = _cache.GetAsync().Result;
if (disco1.IsError) throw new Exception(disco1.Error);
//或者
var disco = tokenCliet.GetDiscoveryDocumentAsync(Authority).Result;
if (disco.IsError) throw new Exception(disco.Error); var response = tokenCliet.RequestPasswordTokenAsync(new PasswordTokenRequest
{
Address = disco.TokenEndpoint,
ClientId = "userinfo_pwd",
ClientSecret = "secret",
//GrantType = "password",
UserName = "cnblogs",
Password = "",
Scope = "apiInfo.read_full"
}).Result; if (response.IsError) throw new Exception(response.Error); var token = response.AccessToken; //把token,Decode
if (response.AccessToken.Contains("."))
{
//Console.WriteLine("\nAccess Token (decoded):");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("\nAccess Token (decoded):");
Console.ResetColor(); var parts = response.AccessToken.Split('.');
var header = parts[];
var claims = parts[]; Console.WriteLine(JObject.Parse(Encoding.UTF8.GetString(Base64Url.Decode(header))));
Console.WriteLine(JObject.Parse(Encoding.UTF8.GetString(Base64Url.Decode(claims))));
}
//设置请求的Token
tokenCliet.SetBearerToken(token);
//请求并返回字符串
var apiResource1 = tokenCliet.GetStringAsync("identity").Result;
var userinfo = tokenCliet.GetStringAsync("identity/userinfo").Result; var j = JObject.Parse(userinfo);
//或者
var getVal = tokenCliet.GetAsync("api/values").Result;
if (getVal.IsSuccessStatusCode)
{
Console.WriteLine(getVal.Content.ReadAsStringAsync().Result);
}
Console.ReadLine();
}
}
}
但自己写一个请求方式,是可以获取到的
HttpClientHepler帮助类,参考网上
public class HttpClientHepler
{
string _url;
public string Url
{
get
{
return _url;
} set
{
_url = value;
}
} public HttpClientHepler(string url)
{
Url = url;
} public async Task GetAsync(string queryString, Action<HttpRequestHeaders> addHeader,
Action<string> okAction = null,
Action<HttpResponseMessage> faultAction = null, Action<Exception> exAction = null)
{
using (HttpClient client = new HttpClient())
{
addHeader(client.DefaultRequestHeaders);
using (HttpResponseMessage response = await client.GetAsync(Url + "?" + queryString))
{
try
{
if (response.IsSuccessStatusCode)
{
okAction(await response.Content.ReadAsStringAsync());
}
else
{
faultAction?.Invoke(response);
}
}
catch (Exception ex)
{
exAction?.Invoke(ex);
}
}
}
} public async Task PostAsync(string queryString, string content, Action<HttpContentHeaders> addHeader,
Action<string> okAction = null,
Action<HttpResponseMessage> faultAction = null, Action<Exception> exAction = null)
{
using (HttpClient client = new HttpClient())
{
using (HttpContent httpContent = new StringContent(content))
{
addHeader(httpContent.Headers);
using (HttpResponseMessage response = await client.PostAsync(Url + "?" + queryString, httpContent))
{
try
{
if (response.IsSuccessStatusCode)
{
okAction(await response.Content.ReadAsStringAsync());
}
else
{
faultAction?.Invoke(response);
}
}
catch (Exception ex)
{
exAction?.Invoke(ex);
}
}
}
}
} }
黄色标记部分是新增代码,运行获取成功
static void Main(string[] args)
{
string Authority = "http://localhost:5003";
string ApiResurce = "http://localhost:5002/";
var tokenCliet = new HttpClient()
{
BaseAddress = new Uri(ApiResurce)
}; /*
这样做的目的是:
资源服务器会去授权服务器认证,所以在客户端可以先判断下授权服务器是否挂了
*/
DiscoveryCache _cache = new DiscoveryCache(Authority);
var disco1 = _cache.GetAsync().Result;
if (disco1.IsError) throw new Exception(disco1.Error);
//或者
var disco = tokenCliet.GetDiscoveryDocumentAsync(Authority).Result;
if (disco.IsError) throw new Exception(disco.Error); //获取token
var AccessToken = "";
var RefreshToken = "";
//通过code获取AccessToken
var client1 = new HttpClientHepler(disco.TokenEndpoint);
client1.PostAsync(null,
"client_id=userinfo_pwd" +
"&client_secret=secret" +
"&grant_type=password" +
"&username=cnblogs" +
"&password=123",
hd => hd.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded"),
rtnVal =>
{
var jsonVal = JsonConvert.DeserializeObject<dynamic>(rtnVal);
AccessToken = jsonVal.access_token;
RefreshToken = jsonVal.refresh_token;
}).Wait(); //用RefreshToken 刷新AccessToken
var responseToken = tokenCliet.RequestRefreshTokenAsync(new RefreshTokenRequest
{
Address = disco.TokenEndpoint, ClientId = "userinfo_pwd",
ClientSecret = "secret",
RefreshToken = RefreshToken
}).Result; var response = tokenCliet.RequestPasswordTokenAsync(new PasswordTokenRequest
{
Address = disco.TokenEndpoint,
ClientId = "userinfo_pwd",
ClientSecret = "secret",
//GrantType = "password",
UserName = "cnblogs",
Password = "",
Scope = "apiInfo.read_full"
}).Result; if (response.IsError) throw new Exception(response.Error); var token = response.AccessToken; //把token,Decode
if (response.AccessToken.Contains("."))
{
//Console.WriteLine("\nAccess Token (decoded):");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("\nAccess Token (decoded):");
Console.ResetColor(); var parts = response.AccessToken.Split('.');
var header = parts[];
var claims = parts[]; Console.WriteLine(JObject.Parse(Encoding.UTF8.GetString(Base64Url.Decode(header))));
Console.WriteLine(JObject.Parse(Encoding.UTF8.GetString(Base64Url.Decode(claims))));
}
//设置请求的Token
tokenCliet.SetBearerToken(token);
//请求并返回字符串
var apiResource1 = tokenCliet.GetStringAsync("identity").Result;
var userinfo = tokenCliet.GetStringAsync("identity/userinfo").Result; var j = JObject.Parse(userinfo);
//或者
var getVal = tokenCliet.GetAsync("api/values").Result;
if (getVal.IsSuccessStatusCode)
{
Console.WriteLine(getVal.Content.ReadAsStringAsync().Result);
}
Console.ReadLine();
}
用RefreshToken刷新也成功
OAuth2认证和授权:ResourceOwnerPassword认证的更多相关文章
- keycloak~账号密码认证和授权码认证
用户名密码登录 POST /auth/realms/demo/protocol/openid-connect/token 请求体 x-www-form-urlencoded grant_type:pa ...
- ASP.NET Core WebAPI中使用JWT Bearer认证和授权
目录 为什么是 JWT Bearer 什么是 JWT JWT 的优缺点 在 WebAPI 中使用 JWT 认证 刷新 Token 使用授权 简单授权 基于固定角色的授权 基于策略的授权 自定义策略授权 ...
- OAuth2.0认证和授权原理
什么是OAuth授权? 一.什么是OAuth协议 OAuth(开放授权)是一个开放标准. 允许第三方网站在用户授权的前提下访问在用户在服务商那里存储的各种信息. 而这种授权无需将用户提供用户名和密 ...
- [转载] OAuth2.0认证和授权原理
转载自http://www.tuicool.com/articles/qqeuE3 什么是OAuth授权? 一.什么是OAuth协议 OAuth(开放授权)是一个开放标准,允许第三方网站在用户授权的前 ...
- 一步步搭建最简单oauth2.0认证和授权
oauth2.0 最早接触这个概念是在做微信订阅号开发.当时还被深深的绕进去,关于oauth2.0的解释网上有好多,而且都讲解的比较详细,下面给大家价格参考资料. http://owin.org/ h ...
- OAuth2认证和授权:AuthorizationCode认证
前面的OAuth2认证,里面的授权服务器都是用的identityserver4搭建的 ids4没有之前一般都是Owin搭建授权服务器,博客园有很多 ids4出来后,一般都是用ids4来做认证和授权了, ...
- OAuth2认证和授权:ClientCredentials认证
1:创建授权服务器项目:AuthorizationServer,添加包:IdentityServer4 2:创建资源服务器项目:ResourcesServer,添加包:IdentityServer4. ...
- OAuth2.0认证和授权以及单点登录
https://www.cnblogs.com/shizhiyi/p/7754721.html OAuth2.0认证和授权机制讲解 2017-10-30 15:33 by shizhiyi, 2273 ...
- OAuth2认证和授权入门
OAuth2四种授权方式 四种授权方式 OAuth 2.0定义了四种授权方式. 密码模式(resource owner password credentials) 授权码模式(authorizatio ...
随机推荐
- C语言 · 8皇后问题改编
8皇后问题(改编) 问题描述 规则同8皇后问题,但是棋盘上每格都有一个数字,要求八皇后所在格子数字之和最大. 输入格式 一个8*8的棋盘. 输出格式 所能得到的最大数字和 样例输入 1 2 3 4 5 ...
- 什么是SPU、SKU、ARPU
这是一篇存档性笔记,我自己存档一下对这3个词的理解.如果你已经明了了这3个词的意思,请直接忽略之 首先,搞清楚商品与单品的区别.例如,iphone是一个单品,但是在淘宝上当很多商家同时出售这个产品的时 ...
- openwrt官方固件怎么中继网络
关键一点,取消勾
- 《转载》RPC入门总结(一)RPC定义和原理
转载:深入浅出 RPC - 浅出篇 转载:RPC框架与Dubbo完整使用 转载:深入浅出 RPC - 深入篇 转载:远程调用服务(RPC)和消息队列(Message Queue)对比及其适用/不适用场 ...
- 谈一谈 MPU6050 姿态融合(转)
姿态角(Euler角)pitch yaw roll飞行器的姿态角并不是指哪个角度,是三个角度的统称.它们是:俯仰.滚转.偏航.你可以想象是飞机围绕XYZ三个轴分别转动形成的夹角. 地面坐标系(eart ...
- java项目(学习和研究)
java项目就是研究,不断的对项目进行迭代,把产品做的越来越好,就是research. 自己想着做一个java项目把,可以类似牛客网,想好自己的预期产品,在设计的过程中可以不断改进和扩展,在做这个项目 ...
- 微信小程序模拟点击出现问题解决方法
move tools=>sensors=>Touch:Device-based 如果不行就换成Touch:force enabled,这俩个选择反复更换试试
- 29、sass
SASS 一.SASS的作用: 方便编写CSS. 二.SASS依赖的环境 : Ruby 三.如何安装SASS? gem install sass gem update sass (更新sass) ge ...
- Dev_GridView:设置列为Button
1. gridview ——run designer ——columns ——columns Edit选择repositoryItemButtonEdit1列 2. 更改colums ——showBu ...
- Python学习之旅(十九)
Python基础知识(18):面向对象高级编程(Ⅰ) 使用__slots__:限制实例的属性,只允许实例对类添加某些属性 (1)实例可以随意添加属性 (2)某个实例绑定的方法对另一个实例不起作用 (3 ...