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 ...
随机推荐
- 解决SVN 每次操作都需要重输入用户名密码问题
把目录C:\Users\当前账号\AppData\Roaming\Subversion\auth下的文件删除,然后重启hbuilder或eclipse工具,重新输入账号密码之后,保存即可解决该问题.
- mysql查询某一个字段是否包含中文字符
在使用mysql时候,某些字段会存储中文字符,或是包含中文字符的串,查询出来的方法是: SELECT col FROM table WHERE length(col)!=char_length(col ...
- 目前(2018年)在北京java程序员平均薪水是多少呢?
1. 这个要看看个人java开发能力,你那个自己带项目做团队的比较高哦 2. 一般来说刚毕业的本科实习生大约在5000左右,干半年基本都张到7.5左右了. 3. Java程序员一般都集中在北京,上海和 ...
- Flask学习笔记(3)--路由
0x01 参数传递 传递参数的语法是: /<参数名>/,然后在视图函数中,也要定义同名的参数. 参数的数据类型: 1.如果没有指定具体的数据类型,那么默认就是使用string 数据类型. ...
- Android的Base64的坑
Base64.encodeToString加密后一直和Apache的对不上,多了换行符,最后使用了NO_WRAP就好了 Base64.encodeToString(src, Base64.URL_SA ...
- Scikit-learn使用总结
在机器学习和数据挖掘的应用中,scikit-learn是一个功能强大的python包.在数据量不是过大的情况下,可以解决大部分问题.学习使用scikit-learn的过程中,我自己也在补充着机器学习和 ...
- Psi Probe 安装及使用说明
这是一款 Tomcat 管理和监控工具,前身是 Lambda Probe.由于 Lambda Probe 2006不再更新,所以 PSI Probe 算是对其的一个 Fork 版本并一直更新至今. g ...
- springboot源码解读01
package org.springframework.web; @javax.servlet.annotation.HandlesTypes({org.springframework.web.Web ...
- gym 101755
别问我为什么现在才发... 我怎么睡醒午觉吃了个饭就晚上九点半了啊????? 真实自闭场,感觉码力严重不足需要补魔. A: #include <bits/stdc++.h> using n ...
- JBPM工作流(四)——管理流程定义
概念: ProcessDefinition,流程定义:一个流程的步骤说明,如一个请假流程.报销流程.是一个规则. ProcessDefinition,流程定义对象,是解析.jpdl.xml文件得到流程 ...