asp.net core IdentityServer4 实现 resource owner password credentials(密码凭证)
前言
OAuth 2.0默认四种授权模式(GrantType)
- 授权码模式(authorization_code)
- 简化模式(implicit)
- 密码模式(resource owner password credentials)
- 客户端模式(client_credentials)
本章主要介绍密码模式(resource owner password credentials),OAuth2.0资源所有者密码授权功能允许客户端将用户名和密码发送到令牌服务,并获得该用户的访问令牌.
认证步骤:
- 用户将用户名密码提供给客户端
- 客户端再将用户名密码发送给授权服务器,请求令牌
- 授权服务器确定判断信息是否有误,返回给客户端令牌
创建授权服务器
创建一个API项目工程,我这边以端口5000的形式进行后面的讲解.
Package
PM> Install-package IdentityServer4 -version 2.5.3
创建一个类Config(配置要保护的资源,和可以访问的API的客户端服务器)
public class Config
{
/// <summary>
/// 定义要保护的资源
/// </summary>
/// <returns></returns>
public static IEnumerable<ApiResource> GetApiResources() {
return new List<ApiResource>
{
new ApiResource("api1","MyApi")
};
}
/// <summary>
/// 定义授权客户端
/// </summary>
/// <returns></returns>
public static IEnumerable<Client> GetClients() {
return new List<Client>
{
new Client(){
ClientId="client",
AllowedGrantTypes=GrantTypes.ResourceOwnerPassword,
ClientSecrets=
{
new Secret("secret".Sha256())
},
AllowedScopes={ "api1",IdentityServerConstants.StandardScopes.OfflineAccess //如果要获取refresh_tokens ,必须在scopes中加上OfflineAccess
},
AllowOfflineAccess=true// 主要刷新refresh_token,
}
};
}
}
此处AllowedGrantTypes需要设置为ResourceOwnerPassword(密码凭证).
配置Startup
再走到ConfigureServices方法注入IdentityServer4服务
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients())
.AddResourceOwnerValidator<ResourceOwnerPasswordValidator>();//注入自定义登录验证
}
IdentityServer4默认提供了两种证书加密配置
AddDeveloperSigningCredential AddTemporarySigningCredential
添加内存ApiResourceAddInMemoryApiResources
添加内存Client AddInMemoryClients
添加自定义登录验证AddResourceOwnerValidator
自定义用户验证
public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
{
public Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
{
if (context.UserName == "test" && context.Password == "test")
{
context.Result = new GrantValidationResult(
subject: context.UserName,
authenticationMethod: OidcConstants.AuthenticationMethods.Password);
}
else
{
//验证失败
context.Result = new GrantValidationResult(
TokenRequestErrors.InvalidGrant,
"invalid custom credential"
);
}
return Task.FromResult(0);
}
}
在Configure方法中添加IdentityServer4服务中间件
app.UseIdentityServer();
创建ApiResource
创建一个客户端项目,这边我将端口设置为5001
Package
PM> Install-package IdentityServer4 -version 2.5.3
配置Startup
在ConfigureServices添加认证服务器地址
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:5000";//授权服务器地址
options.RequireHttpsMetadata = false;//不需要https
options.ApiName = "api1";
});
}
在Configure方法中添加认证服务中间件
app.UseAuthentication();
Run
在客户端程序values控制器上面增加[Authorize]
直接访问资源服务器http://localhost:5001/api/values

code 401
启动授权服务器
http://localhost:5000/.well-known/openid-configuration
发现端点可通过/.well-known/openid-configuration

获取token
这边我用postman进行测试

code 200
access_token我们获取到了,再拿着token通过postman请求资源程序,

code 200
成功了
refresh_token
获取请求授权接口后会返回access_token expires
_in 等内容,expires_in是有效期(s),当然我们可以自定义有效期,access_token失效后用户需要重新授权,client才能拿到新的access_token.但是有了refresh_token后,client检测到token失效后可以直接通过refresh_token向授权服务器申请新的token,当然refresh_token也是有有效期的。
AbsoluteRefreshTokenLifetime的默认有效期为2592000秒/30天。SlidingRefreshTokenLifetime的默认有效期为1296000秒/15天。
在认证服务器中我再scopes加上了OfflineAccess
IdentityServerConstants.StandardScopes.OfflineAccess //如果要获取refresh_tokens ,必须在scopes中加上OfflineAccess
获取refresh_token

通过refresh_token再去获取access_token

通过postman请求获取资源

概要
示例地址https://github.com/fhcodegit/IdentityServer4.Samples
asp.net core IdentityServer4 实现 resource owner password credentials(密码凭证)的更多相关文章
- IdentityServer4之Resource Owner Password Credentials(资源拥有者密码凭据许可)
IdentityServer4之Resource Owner Password Credentials(资源拥有者密码凭据许可) 参考 官方文档:2_resource_owner_passwords ...
- IdentityServer4 之 Resource Owner Password Credentials 其实有点尴尬
前言 接着IdentityServer4的授权模式继续聊,这篇来说说 Resource Owner Password Credentials授权模式,这种模式在实际应用场景中使用的并不多,只怪其太开放 ...
- 基于OWIN WebAPI 使用OAuth授权服务【客户端验证授权(Resource Owner Password Credentials Grant)】
适用范围 前面介绍了Client Credentials Grant ,只适合客户端的模式来使用,不涉及用户相关.而Resource Owner Password Credentials Grant模 ...
- 不要使用Resource Owner Password Credentials
不要使用Resource Owner Password Credentials 文章链接在这里 前言 最近公司项目在做一些重构,因为公司多个业务系统各自实现了一套登录逻辑,比较混乱.所以,现在需要做一 ...
- 使用Resource Owner Password Credentials Grant授权发放Token
对应的应用场景是:为自家的网站开发手机 App(非第三方 App),只需用户在 App 上登录,无需用户对 App 所能访问的数据进行授权. 客户端获取Token: public string Get ...
- 基于 IdentityServer3 实现 OAuth 2.0 授权服务【密码模式(Resource Owner Password Credentials)】
密码模式(Resource Owner Password Credentials Grant)中,用户向客户端提供自己的用户名和密码.客户端使用这些信息,向"服务商提供商"索要授权 ...
- OAuth2.0学习(1-6)授权方式3-密码模式(Resource Owner Password Credentials Grant)
授权方式3-密码模式(Resource Owner Password Credentials Grant) 密码模式(Resource Owner Password Credentials Grant ...
- IdentityServer4专题之六:Resource Owner Password Credentials
实现代码: (1)IdentityServer4授权服务器代码: public static class Config { public static IEnumerable<Identity ...
- ABP中使用OAuth2(Resource Owner Password Credentials Grant模式)
ABP目前的认证方式有两种,一种是基于Cookie的登录认证,一种是基于token的登录认证.使用Cookie的认证方式一般在PC端用得比较多,使用token的认证方式一般在移动端用得比较多.ABP自 ...
随机推荐
- 良许Linux | Linux学习方法及学习资料汇总
很多人想学习Linux,却不知道怎么着手,甚至不知道Linux有哪些方向,非常迷茫.基于此,我特地写了篇文章介绍Linux方向性问题,没想到一不小心成了爆款: 到什么程度才叫精通 Linux? 看完 ...
- vector function trmplate
/* vector function template programmer:qpz */ #include <iostream> #include <vector> #def ...
- C/C++ 修改系统时间,导致sem_timedwait 一直阻塞的问题解决和分析
修改系统时间,导致sem_timedwait 一直阻塞的问题解决和分析 介绍 最近修复项目问题时,发现当系统时间往前修改后,会导致sem_timedwait函数一直阻塞.通过搜索了发现int sem_ ...
- Java网络编程之UDP
Java网络编程之UDP 一.C/S架构中UDP网络通信流程 ①创建DatagramSocket与DatagramPacket对象 ②建立发送端,接收端 ③建立数据包 ④调用Socket的发送.接收方 ...
- 【Leetcode】【简单】【17. 整数反转】【JavaScript】
题目描述 7. 整数反转 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转. 示例 1: 输入: 123输出: 321 示例 2: 输入: -123输出: -321示例 3: 输 ...
- Springboot源码分析之事务问题
摘要: 事务在后端开发中无处不在,是数据一致性的最基本保证.要明白进事务的本质就是进到事务切面的代理方法中,最常见的是同一个类的非事务方法调用一个加了事务注解的方法没进入事务.我们以cglib代理为例 ...
- 【Appium】Appium+Python环境搭建
环境准备: 1.jdk 2.android-sdk 3.python 4.Node.js 5.appium 6.Appium-Python-Client 1. 下载jdk1.7:http://www. ...
- P2059 [JLOI2013]卡牌游戏 概率DP
link:https://www.luogu.org/problemnew/show/P2059 题意: 有n个人,类似约瑟夫环的形式踢人,但是报的数是不同的,是在给定的许多数中随机抽取,问最后第i个 ...
- HDU 4607 Park Visit 树的最大直径
题意: 莱克尔和她的朋友到公园玩,公园很大也很漂亮.公园包含n个景点通过n-1条边相连.克莱尔太累了,所以不能去参观所有点景点. 经过深思熟虑,她决定只访问其中的k个景点.她拿出地图发现所有景点的入口 ...
- hdu 1078 FatMouse and Cheese(简单记忆化搜索)
题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=1078 题意:给出n*n的格子,每个各自里面有些食物,问一只老鼠每次走最多k步所能吃到的最多的食物 一道 ...