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 ...
随机推荐
- [转]decorator(HTML装饰器)
原文地址:https://blog.csdn.net/jzh440/article/details/7770013 1>:每当遇到一个新的技术,首先我会问自己,这个技术是做神马的?用这个技术有神 ...
- neo1973 audio subsystem
fhttp://wiki.openmoko.org/wiki/Neo_1973_audio_subsystem using Bluetooth headset with GSM NOTE none o ...
- spark StructType的应用,用在处理mongoDB keyvalue
近期在处理mongoDB 数据的时候,遇到了非常奇怪的格式,账号密码的日志都追加在一条记录里面,要取一个密码的时长和所有密码的平均时长就非常繁琐. 用了各种迭代计算,非常困难,而且printschem ...
- Cesium简单使用
CesiumJS是一个基于javascript的浏览器器3d地图引擎 下载 https://cesiumjs.org/downloads/ 下载的Cesium-1.56.1,解压后的结构为 1.设置W ...
- linux windows安装python的最佳方式,miniconda
1.在linux安装python文章很多,但是步骤很多,没搞好还会把yum命令弄坏,要修复.这件事就发生在我身上,准确说不是我造成的,是总监自己安装python造成yum损坏的,然后需要运维去百度修改 ...
- 在iPhone手机上写了input type="date" 显示不出来的原因
在iPhone手机上写了input type="date" 显示不出来的原因 今天在手机页面上使用新的input类型,这样子写,在chrome浏览器上浏览,很好,显示出来.然后用i ...
- ORACLE调优深入理解AWR报告(转)
AWR报告分析可从以下几点入手: (1).Oacle主机资源开销分析及负载情况 (2).oracle top信息分析 Top 10 Foreground Events by Total Wait Ti ...
- php操作redis案例
<?php //实例化 $redis = new Redis(); //连接服务器 //默认端口是6379,可不写 $redis->connect( ...
- react 中的绑定事件
handleOpen = (e)=> { this.setState({ open: true }) } <Button color='primary' onClick={this.han ...
- linux的基本操作(正则表达式)
正则表达式 这部分内容可以说是学习shell脚本之前必学的内容.如果你这部分内容学的越好,那么你的shell脚本编写能力就会越强.所以不要嫌这部分内容啰嗦,也不要怕麻烦,要用心学习.一定要多加练习,练 ...