IdentityServer(三)密码模式
前言
用户名密码模式相较于客户端凭证模式,多了用户。通过用户的用户名和密码向Identity Server申请访问令牌。密码模式有两种实现方式.
1.把用户写进内存Identity从中读取账号密码验证
AddInMemoryUsers(config.GetUsers())
2.通过实现 IResourceOwnerPasswordValidator 接口来验证用户
AddResourceOwnerValidator(ResourcePasswordValidator)
第二种更加实用灵活,这篇笔记也是实现的第二种。

实现用户名密码授权
我们在之前的搭建好的Identity服务上新增一个名为 ResourcePasswordValidator 的类继承 IResourceOwnerPasswordValidator 重写ValidateAsync 方法来验证用户名和密码
using System.Security.Claims;
using System.Threading.Tasks;
using IdentityModel;
using IdentityServer4.Models;
using IdentityServer4.Validation;
namespace IdentityServer
{
public class ResourcePasswordValidator: IResourceOwnerPasswordValidator
{
public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
{
//判断账号密码是否正确。
if (context.UserName == "userName" && context.Password == "1234567")
{
context.Result = new GrantValidationResult(
subject: "userInfo",
authenticationMethod: OidcConstants.AuthenticationMethods.Password,
claims: GetUserClaims());
}
else
{
//验证失败
context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "invalid custom credential");
}
}
//可以根据需要设置相应的Claim/需要实现IProfileService接口
private Claim[] GetUserClaims()
{
return new Claim[]
{
new Claim("userId","110"),
new Claim(JwtClaimTypes.Name,"林辉"),
new Claim(JwtClaimTypes.Role,"菜鸡")
};
}
}
}
在 Config.cs 中新增一个客户端
new Client
{
ClientId = "client_b",
AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
//AccessToken过期时间(秒),默认为3600秒/1小时
AccessTokenLifetime=3600,
//RefreshToken的最长生命周期
//AbsoluteRefreshTokenLifetime = 2592000,
//RefreshToken生命周期以秒为单位。默认为1296000秒
SlidingRefreshTokenLifetime = 2592000,//以秒为单位滑动刷新令牌的生命周期。
//刷新令牌时,将刷新RefreshToken的生命周期。RefreshToken的总生命周期不会超过AbsoluteRefreshTokenLifetime。
RefreshTokenExpiration = TokenExpiration.Sliding,
//AllowOfflineAccess 允许使用刷新令牌的方式来获取新的令牌
AllowOfflineAccess = true,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = { "Api"}
}
新建一个 ProfileService 来实现 IProfileService 接口来扩展自定义Claim
using System;
using System.Linq;
using System.Threading.Tasks;
using IdentityServer4.Models;
using IdentityServer4.Services;
namespace IdentityServer
{
public class ProfileService : IProfileService
{
public async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
try
{
//depending on the scope accessing the user data.
var claims = context.Subject.Claims.ToList();
//set issued claims to return
context.IssuedClaims = claims.ToList();
}
catch (Exception ex)
{
//log your error
}
}
public async Task IsActiveAsync(IsActiveContext context)
{
context.IsActive = true;
}
}
}
修改 Startup
//注入DI
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryIdentityResources(Config.GetIdentityResourceResources())
.AddInMemoryApiResources(Config.GetApiResources())//Api资源信息
.AddInMemoryClients(Config.GetClients())//客户端信息
.AddResourceOwnerValidator<ResourcePasswordValidator>()//用户验证
.AddProfileService<ProfileService>();//扩展claims
测试效果
通过用户名密码申请令牌

当access_token过期的时候通过refresh_token来刷新access_token,refresh_token只能使用一次,每次刷新后会返给信的refresh_token和access_token

我们通过jwt.io解析出来。可以发现jwt里面包含了我们添加的身份信息,这些信息可以直接在资源服务器中获取使用

修改资源服务器
我们在Api中可以通过 User.Claims.FirstOrDefault(m => m.Type == "userId").value; 获取我们用户身份信息。
[HttpGet("userInfo")]
[Authorize]
public ActionResult UserIno()
{
return new JsonResult($"用户id{User.Claims.FirstOrDefault(m => m.Type == "userId").Value }" );
}

IdentityServer(三)密码模式的更多相关文章
- docker-compose一键部署redis一主二从三哨兵模式(含密码,数据持久化)
本篇基于centos7服务器进行部署开发 一.拉取redis镜像,使用如下命令 docker pull redis 1.查看镜像是否拉取成功,使用如下命令 docker images 显示如下则证明拉 ...
- 【ASP.NET Core分布式项目实战】(一)IdentityServer4登录中心、oauth密码模式identity server4实现
本博客根据http://video.jessetalk.cn/my/course/5视频整理 资料 OAuth2 流程:http://www.ruanyifeng.com/blog/2014/05/o ...
- IdentityServer4 密码模式认证
授权服务器设置 添加用户 添加测试用户,也可以从数据库查 public static List<TestUser> GetTestUser() { return new List< ...
- asp.net core 使用identityServer4的密码模式来进行身份认证(一)
IdentityServer4是ASP.NET Core的一个包含OpenID和OAuth 2.0协议的框架.具体Oauth 2.0和openId请百度. 前言本博文适用于前后端分离或者为移动产品来后 ...
- IdentityServer4 实现OAuth2.0四种模式之密码模式
接上一篇:IdentityServer4 实现OAuth2.0四种模式之客户端模式,这一篇讲IdentityServer4 使用密码模式保护API访问. 一,IdentityServer配置 1,添加 ...
- 基于 IdentityServer3 实现 OAuth 2.0 授权服务【密码模式(Resource Owner Password Credentials)】
密码模式(Resource Owner Password Credentials Grant)中,用户向客户端提供自己的用户名和密码.客户端使用这些信息,向"服务商提供商"索要授权 ...
- 【运维技术】redis(一主两从三哨兵模式搭建)记录
redis(一主两从三哨兵模式搭建)记录 目的: 让看看这篇文章的的人能够知道:软件架构.软件的安装.配置.基本运维的操作.高可用测试.也包含我自己,能够节省对应的时间. 软件架构: 生产环境使用三台 ...
- IdentityServer4:IdentityServer4+API+Client+User实践OAuth2.0密码模式(2)
一.密码模式实操 仍然使用第一节的代码:做如下改动: 1.授权服务端 前面我们使用项目:Practice.IdentityServer作为授权服务器 修改项目的Config.cs类: 添加测试用户,并 ...
- IdentityServer4 密码模式实现
1. 修改 Config.cs using System.Collections; using System.Collections.Generic; using IdentityServer4.M ...
随机推荐
- 基于 Spring + Atomikos + Mybatis的多数据源配置demo
1.spring配置文件 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns=" ...
- springboot集成webSocket能启动,但是打包不了war
1.pom.xml少packing元素 https://www.cnblogs.com/zeussbook/p/10790339.html 2.SpringBoot项目中增加了WebSocket功能无 ...
- mysql 数据库批量刷新表字段数据
UPDATE a,bSET b.studentno = a.studentnumber WHERE b.studentno IS NULL AND a.p_id = b.p_id
- [转载]oracle xml操作
/*=====================生成\修改xml========================= */ --xmlelement多个标签层级 SELECT XMLELEMENT(&qu ...
- Max coverage disjoint intervals
Assume you have k<=10^5 intervals [a_i, b_i] \in [1,10^18] (some of them may overlap), and you ne ...
- [转帖]为何 CPU 只用硅,而不用能耗更低的锗制作?知乎好文章
作者:鲁超链接:https://www.zhihu.com/question/28935966/answer/617701106来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明 ...
- windows安装memcache并为php添加memcache扩展
第一步:安装包下载 1.4.5 版本之前用作为一个服务安装,1.4.5 版本之后用任务计划中启用一个普通进程来使用 具体内容如以下链接:http://www.runoob.com/memcached/ ...
- 只学python行吗
常言道:"流水的语言,铁打的Python",目前它可以说是已经"睥睨天下,傲视群雄"了.它天生丽质,易于读写,非常实用,从而赢得了 广泛的群众基础,被誉为&qu ...
- golang字符串常用的系统函数
1.统计字符串的长度,按字节len(str) str := "hello北京" fmt.Println("str len=", len(str)) 2.字符串遍 ...
- Python之正则表达式笔记
概述 概念 Regular Expression 一种文本模式,描述在搜索文本时要匹配的一个或多个字符串 典型场景 数据验证.文本扫描.文本提取.文本替换.文本分割 语法 字面值 普通字符 需转义:\ ...