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. 产品设计利器--axure

    1.axute的使用方法: 2.普通线框图的使用: 3.高保真原型图: 4.交互思维. Axure RP8 是美国Axure Software Solution公司的旗舰产品,是一个快速的原型工具,主 ...

  2. 使用import scope解决maven继承(单)问题<转>

    测试环境 maven 3.3.9 想必大家在做SpringBoot应用的时候,都会有如下代码: <parent> <groupId>org.springframework.bo ...

  3. 光纤网卡、HBA卡和RAID卡的区别(图)

    原文地址:http://wenku.baidu.com/link?url=suuaTXbO_HXeNvuEfi8_RhRAfhQdoZ854lEK4K6LKprgQwwuxA-i3ItwPn7BBBK ...

  4. zoj 3430 Detect the Virus(AC自己主动机)

    Detect the Virus Time Limit: 2 Seconds      Memory Limit: 65536 KB One day, Nobita found that his co ...

  5. 加载所有jar包下指定文件

    加载所有jar包下指定文件: 如spring中加载 META-INF/spring.handlers 加载 org.springframework.core.io.support.Properties ...

  6. 04Hadoop中的setPartitionerClass/SortComparator/GroupingComparator问题

    map阶段 1. 使用job.setInputFormatClass(TextInputFormat)做为输入格式.注意输出应该符合自定义Map中定义的输出. 2. 进入Mapper的map()方法, ...

  7. 【Clojure 基本知识】小技巧s

    ;;模拟console原位更新输出 ;;空格擦除法,输出空格,是为了擦除短字符串尾部没有占用的位置,因为退格只是回退,并不删除(dotimes [_ 10](let [n (rand) sn (.su ...

  8. node-sass 安装失败 Failed at the node-sass@4.9.2 postinstall script的解决

    控制台运行npm install时报错,报错信息如下: npm ERR! code ELIFECYCLEnpm ERR! errno 1npm ERR! node-sass@4.9.2 postins ...

  9. 并发编程基础之ThreadLocal

    一:概念 在多线程并发访问的情况下,为了解决线程安全,一般我们会使用synchronized关键字,如果并发访问量不是很大,可以使用synchronized, 但是如果数据量比较大,我们可以考虑使用T ...

  10. [3]java1.8线程池—ThreadPoolExecutor

    Wiki 上是这样解释的:Thread Pool 作用:利用线程池可以大大减少在创建和销毁线程上所花的时间以及系统资源的开销! 下面主要讲下线程池中最重要的一个类 ThreadPoolExecutor ...