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 ...
随机推荐
- eNSP——静态路由的基本配置
原理: 静态路由是指用户或网络管理员手工配置的路由信息.当网络的拓扑结构或链路状态发生改变时,需要网络管理人员手工修改静态路由信息. 相比于动态路由协议,静态路由无需频繁地交换各自的路由表,配置简单, ...
- 阿里云RocketMQ的消费者简单实现
业务场景之类的请看另一篇生产者的实现: package com.ttt.eee; import com.aliyun.openservices.ons.api.Action; import com.a ...
- [转帖]nginx location配置详细解释
nginx location配置详细解释 http://outofmemory.cn/code-snippet/742/nginx-location-configuration-xiangxi-exp ...
- DB2输出每隔10分钟的数据
一.输出1-100的数据 此处参考 https://bbs.csdn.net/topics/390516027 with t(id) as ( as id from sysibm.sysdummy1 ...
- java中不常见的关键字:strictfp
1.strictfp, 即 strict float point (精确浮点). strictfp 关键字可应用于类.接口或方法.使用 strictfp 关键字声明一个方法时,该方法中所有的float ...
- Python连接ORACLE操作
一.准备工作 1.安装cx_Oracle ttps://pypi.python.org/pypi下查找cx_Oracle并下载 执行安装命令 pip install cx_Oracle-6.0rc1- ...
- 探索grafana
因为zabbix的监控图形不够美观,功能也不够强大, 那么就用到了grafana 填写zabbix插件配置: 如下需要根据主机群组和主机名来完成图形: grafana报警如下: 解决如下: 更改标准设 ...
- IntelliJ Idea基于Maven创建SpringMVC程序
1. 创建Maven工程 网上很多资料,不再详细介绍,请参看IntelliJ IDEA 创建 hello world Java web Maven项目从头到尾都有图有真相2017版本 有关settin ...
- go 函数闭包
Go 函数可以是闭包的.闭包是一个函数值,它来自函数体的外部的变量引用. 函数可以对这个引用值进行访问和赋值:换句话说这个函数被“绑定”在这个变量上. 例如,函数 adder 返回一个闭包.每个闭包都 ...
- [javascript]原生js实现Ajax
一.首先看JQuery提供的Ajax方法: $.ajax({ url: , type: '', dataType: '', data: { }, success: function(){ }, err ...