ASP.NET Core的身份认证框架IdentityServer4--(5)自定义用户登录(通过接口登录,无UI版本)
官网接口详解文档地址:文档地址 (PS:可通过接口名称搜索相应接口信息。)
源码地址:https://github.com/YANGKANG01/IdentityServer4-IdentityAuth
一、修改服务端
1、修改Startup文件源码如下:
namespace Server
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
//配置身份服务器与内存中的存储,密钥,客户端和资源
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryIdentityResources(Config.GetIdentityResources());//添加对OpenID Connect的支持
.AddInMemoryApiResources(Config.GetApiResources())//添加api资源
.AddInMemoryClients(Config.GetClients())//添加客户端
.AddResourceOwnerValidator<LoginValidator>()//用户校验
.AddProfileService<ProfileService>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//添加到HTTP管道中。
app.UseIdentityServer();
}
}
}
2、修改config文件
namespace Server
{
public class Config
{
/// <summary>
/// 添加对OpenID Connect的支持
/// </summary>
/// <returns></returns>
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource>
{
new IdentityResources.OpenId(), //必须要添加,否则报无效的scope错误
new IdentityResources.Profile()
};
}
/// <summary>
/// 范围定义系统中的API资源
/// </summary>
/// <returns></returns>
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource("api1", "My API")
};
} /// <summary>
/// 客户想要访问资源(又称范围)
/// </summary>
/// <returns></returns>
public static IEnumerable<Client> GetClients()
{
// 客户端信息
return new List<Client>
{
//自定义客户端
new Client
{
//客户端名称
ClientId = "client1",
//客户端访问方式:密码验证
AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
//用于认证的密码加密方式
ClientSecrets =
{
new Secret("secret".Sha256())
},
//客户端有权访问的范围
AllowedScopes = { "api1",IdentityServerConstants.StandardScopes.OpenId, //必须要添加,否则报403 forbidden错误
IdentityServerConstants.StandardScopes.Profile }
}
};
}
}
}
3、新建LoginValidator类,用于用户校验
namespace Server
{
/// <summary>
/// 自定义用户登录校验
/// </summary>
public class LoginValidator : IResourceOwnerPasswordValidator
{
public LoginValidator()
{ }
/// <summary>
/// 登录用户校验
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
{
//根据context.UserName和context.Password与数据库的数据做校验,判断是否合法
if (context.UserName == "test" && context.Password == "")
{
context.Result = new GrantValidationResult(
subject: context.UserName,
authenticationMethod: "custom",
claims: GetUserClaims());
}
else
{
//验证失败
context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "账号密码错误");
}
}
/// <summary>
/// 可以根据需要设置相应的Claim
/// </summary>
/// <returns></returns>
private Claim[] GetUserClaims()
{
return new Claim[]
{
new Claim("UserId", .ToString()),
new Claim(JwtClaimTypes.Name,"test"),
new Claim(JwtClaimTypes.GivenName, "jaycewu"),
new Claim(JwtClaimTypes.FamilyName, "yyy"),
new Claim(JwtClaimTypes.Email, "test@qq.com"),
new Claim(JwtClaimTypes.Role,"admin")
};
}
}
}
4、新建ProfileService类,用于返回用户自定义信息
namespace Server
{
/// <summary>
/// 获取用户信息并返回给客户端
/// </summary>
public class ProfileService : IProfileService
{
/// <summary>
/// 获取用户信息
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
try
{
//用户信息
var claims = context.Subject.Claims.ToList(); //获取用户信息
context.IssuedClaims = claims.ToList();
}
catch (Exception ex)
{
//log your error
}
}
/// <summary>
/// 获取或设置一个值,该值指示主题是否处于活动状态并且可以接收令牌。
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public async Task IsActiveAsync(IsActiveContext context)
{
context.IsActive = true;
}
}
}
5、通过接口获取用户信息
5.1、用户登录接口:http://localhost:5000/connect/token
| 参数名 | 说明 | 是否必填 | 示例 |
| username | 用户名 | Y | test |
| password | 密码 | Y | 123 |
| grant_type | 加密类型 | Y | password |
| client_id | 客户端名称 | Y | client1 |
| client_secret | 客户端加密类型 | Y | secret |
效果图:

5.2、获取用户信息接口:http://localhost:5000/connect/userinfo
| 参数 | 是否必填 | 说明 |
| Authorization | Y | 值的格式:key空格value |
PS:key 的值为上面接口返回的 token_type 的值,value 为 access_token 的值。
通过调用上面两个接口,完成登录授权。
效果图:

ASP.NET Core的身份认证框架IdentityServer4--(5)自定义用户登录(通过接口登录,无UI版本)的更多相关文章
- ASP.NET Core的身份认证框架IdentityServer4(7)- 使用客户端证书控制API访问
前言 今天(2017-9-8,写于9.8,今天才发布)一口气连续把最后几篇IdentityServer4相关理论全部翻译完了,终于可以进入写代码的过程了,比较累.目前官方的文档和Demo以及一些相关组 ...
- ASP.NET Core的身份认证框架IdentityServer4(1)-特性一览
IdentityServer4是ASP.NET Core的一个包含OpenID和OAuth 2.0协议的框架.OpenID和OAuth 的区别请看 https://www.zhihu.com/ques ...
- ASP.NET Core的身份认证框架IdentityServer4(6)- 开始
安装和概述 启动一个新的IdentityServer项目有两种基本方法: 从头开始 从Visual Studio中的ASP.NET身份模板开始 如果从头开始,我们提供了一些文档.项目帮助和内存存储支持 ...
- ASP.NET Core的身份认证框架IdentityServer4(5)- 包和构建
包和构建 IdentityServer有许多nuget包 IdentityServer4 nuget | github 包含IdentityServer核心对象模型,服务和中间件. 仅支持内存配置和用 ...
- ASP.NET Core的身份认证框架IdentityServer4(9)-使用OpenID Connect添加用户认证
OpenID Connect OpenID Connect 1.0是OAuth 2.0协议之上的一个简单的身份层. 它允许客户端基于授权服务器执行的身份验证来验证最终用户的身份,以及以可互操作和类似R ...
- ASP.NET Core的身份认证框架IdentityServer4(3)-术语的解释
IdentityServer4 术语 IdentityServer4的规范.文档和对象模型使用了一些你应该了解的术语. 身份认证服务器(IdentityServer) IdentityServer是一 ...
- ASP.NET Core的身份认证框架IdentityServer4(8)- 使用密码认证方式控制API访问
前言 本文及IdentityServer这个系列使用的都是基于.net core 2.0的.上一篇博文在API项目中我使用了icrosoft.AspNetCore.Authentication.Jwt ...
- ASP.NET Core的身份认证框架IdentityServer4(4)- 支持的规范
IdentityServer实现以下规范: OpenID Connect OpenID Connect Core 1.0 (spec) OpenID Connect Discovery 1.0 (sp ...
- ASP.NET Core的身份认证框架IdentityServer4--入门
ASP.NET Core的身份认证框架IdentityServer4--入门 2018年08月11日 10:09:00 qq_42606051 阅读数 4002 https://blog.csdn ...
- ASP.NET Core的身份认证框架IdentityServer4--入门【转】
原文地址 Identity Server 4是IdentityServer的最新版本,它是流行的OpenID Connect和OAuth Framework for .NET,为ASP.NET Cor ...
随机推荐
- The Bits (思维+找规律)
Description Rudolf is on his way to the castle. Before getting into the castle, the security staff a ...
- LeetCode 36. Valid Sudoku (C++)
题目: Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according t ...
- Scrum立会报告+燃尽图(Beta阶段第二周第五次)
此作业要求参见:https://edu.cnblogs.com/campus/nenu/2018fall/homework/2413 项目地址:https://coding.net/u/wuyy694 ...
- Linux系统LVS搭建笔记
因为客户是国有企业,且一次性购买了14台服务器(16核),14台中暂且先用8台,其中LVS使用5台,NFS一台主要为了共享WEB系统(多台电脑的1.5T的硬盘容量浪费了).MySQL两台,Memcac ...
- HttpCookie Class
提供创建和操作各 HTTP Cookie 的类型安全方法. #region 写入指定Cookie的值 +static void WriteCookie(string cookieName, strin ...
- python、Eclipse、pydev环境配置
转载来源:http://www.cnblogs.com/Bonker/p/3584707.html 编辑器: Eclipse + pydev插件: 1. Eclipse是写JAVA的IDE, 这样就可 ...
- LR监控tomcat服务器
采用编写VuGen脚本访问Tomcat的Status页面的方式获取性能数据(利用了关联和lr_user_data_point函数),本质上还是使用tomcat自带的监控页面,只是将监控结果加到LR的a ...
- Geek荣耀大会总结
0.0 首先没有被抽中, 其次可乐真难喝,再次我没有去拍无人机合影,再再次还是很受打击的. 1.0 其实 对geek 和1024大会无感,主要原因 没有三倍加班费的节日在我眼里都不是节日. 上面只是简 ...
- Django之ORM对数据库操作
基本操作 <1> all(): 查询所有结果 <2> filter(**kwargs): 它包含了与所给筛选条件相匹配的对象 <3> get(**kwargs): ...
- 【EF】Entity Framework Core 命名约定
本文翻译自<Entity Framework Core: Naming Convention>,由于水平有限,故无法保证翻译完全正确,欢迎指出错误.谢谢! 注意:我使用的是 Entity ...