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认证的更多相关文章

  1. keycloak~账号密码认证和授权码认证

    用户名密码登录 POST /auth/realms/demo/protocol/openid-connect/token 请求体 x-www-form-urlencoded grant_type:pa ...

  2. ASP.NET Core WebAPI中使用JWT Bearer认证和授权

    目录 为什么是 JWT Bearer 什么是 JWT JWT 的优缺点 在 WebAPI 中使用 JWT 认证 刷新 Token 使用授权 简单授权 基于固定角色的授权 基于策略的授权 自定义策略授权 ...

  3. OAuth2.0认证和授权原理

    什么是OAuth授权?   一.什么是OAuth协议 OAuth(开放授权)是一个开放标准. 允许第三方网站在用户授权的前提下访问在用户在服务商那里存储的各种信息. 而这种授权无需将用户提供用户名和密 ...

  4. [转载] OAuth2.0认证和授权原理

    转载自http://www.tuicool.com/articles/qqeuE3 什么是OAuth授权? 一.什么是OAuth协议 OAuth(开放授权)是一个开放标准,允许第三方网站在用户授权的前 ...

  5. 一步步搭建最简单oauth2.0认证和授权

    oauth2.0 最早接触这个概念是在做微信订阅号开发.当时还被深深的绕进去,关于oauth2.0的解释网上有好多,而且都讲解的比较详细,下面给大家价格参考资料. http://owin.org/ h ...

  6. OAuth2认证和授权:AuthorizationCode认证

    前面的OAuth2认证,里面的授权服务器都是用的identityserver4搭建的 ids4没有之前一般都是Owin搭建授权服务器,博客园有很多 ids4出来后,一般都是用ids4来做认证和授权了, ...

  7. OAuth2认证和授权:ClientCredentials认证

    1:创建授权服务器项目:AuthorizationServer,添加包:IdentityServer4 2:创建资源服务器项目:ResourcesServer,添加包:IdentityServer4. ...

  8. OAuth2.0认证和授权以及单点登录

    https://www.cnblogs.com/shizhiyi/p/7754721.html OAuth2.0认证和授权机制讲解 2017-10-30 15:33 by shizhiyi, 2273 ...

  9. OAuth2认证和授权入门

    OAuth2四种授权方式 四种授权方式 OAuth 2.0定义了四种授权方式. 密码模式(resource owner password credentials) 授权码模式(authorizatio ...

随机推荐

  1. 基于expressjs老项目的翻新方案

    刚开始接触这方面的项目时,对ES规范理解不深,查了一些资料,发现如果不改expressjs的代码,大概率是没法用到最新的async/await了,后续也就没有继续往这个方面想. 这两天突然想起这个问题 ...

  2. 怎么让self.view的Y从navigationBar下面开始计算

    原文地址 http://blog.sina.com.cn/s/blog_1410870560102wu9a.html 在iOS 7中,苹果引入了一个新的属性,叫做[UIViewController s ...

  3. HTML 09 web 内容与攻击技术

    Servlet 改进 CGI 之前提及的 CGI, 由于每次接到请求, 程序都要跟着启动一次, 因此一旦访问量过大, web 服务器要承担低昂当大的负载, 而 servlet 运行在与 web 服务器 ...

  4. Git分支操作——查看、新建、删除、提交、合并

    查看分支 1 查看本地分支 $ git branch   2 查看远程分支 $ git branch -r     创建分支 1 创建本地分支 $ git branch branchName 2 切换 ...

  5. Linux iptables原理和使用

    1.原理 iptables简介 netfilter/iptables(简称为iptables)组成Linux平台下的包过滤防火墙,与大多数的Linux软件一样,这个包过滤防火墙是免费的,它可以代替昂贵 ...

  6. TCP是如何保证可靠传输的

    TCP 协议如何保证可靠传输   一.综述 1.确认和重传:接收方收到报文就会确认,发送方发送一段时间后没有收到确认就重传. 2.数据校验 3.数据合理分片和排序: UDP:IP数据报大于1500字节 ...

  7. Axure RP 9 Beta 开放下载(更新激活密钥和汉化包)

    2018年9月9号,7月9号来厦门入职,已经两个月了.这两个月的生活状态真心不好,一方面工作很忙(刚工作是这样?),虽然工资还可以,但总感觉性价比很低,自已对这份工作不够热爱也许.另一方面,来到新城市 ...

  8. http://www.rehack.cn/techshare/webbe/php/3391.html

    首先配置好本地PHPstudy环境: 默认在D:\phpStudy\php\php-7.0.12-nts\ext目录下有php_pdo_sqlsrv_7_nts_x86.dll.php_sqlsrv_ ...

  9. [原]Docker-issue(1) image name 显示为 <none>

    问题:今天发现重新上传新的image的时候覆盖了原来的镜像后,REPOSITORY 就变为了 <none> ,如下图 解决办法: 使用tag重新命名image 问题解决:

  10. 解决JS(Vue)input[type='file'] change事件无法上传相同文件的问题

    Html <input id="file" type="file" accept=".map" onchange="uplo ...