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 ...
随机推荐
- LeetCode 454. 4Sum II (C++)
题目: Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are su ...
- 四则运算——单元测试(测试方法:Right-BICEP )
一.测试的具体部位 Right-结果是否正确? B-是否所有的边界条件都是正确的? I-能查一下反向关联吗? C-能用其他手段交叉检查一下结果吗? E-你是否可以强制错误条件发生? P-是否满足性能要 ...
- 记录 C++ STL 中 一些好用的函数--持续更新 (for_each,transform,count_if,find_if)
在日常的编程中,有这么几种操作还是比较常见的: 把一组数据都赋值成一个数,在一组数据中查找一个数,统计一组数据中符合条件的数等等. 一般的写法可以用循环,没有什么是循环不能搞定的.假如在这里怎么用介绍 ...
- spring框架(3)— spring集合类的注入
1.Car.java package com.eniac.beans; public class Car { private String type; private String factory; ...
- Java clone() 浅拷贝 深拷贝
假如说你想复制一个简单变量.很简单: int apples = 5; int pears = apples; 不仅仅是int类型,其它七种原始数据类型(boolean,char,byte,short, ...
- java沙盒入门
程序员写一个Java程序,默认的情况下你可以访问任意的机器资源,比如读取,删除一些文件或者网络操作等.当你把程序部署到正式的服务器上,系统管理员要为服务器的安全承担责任,那么他可能不敢确定你的程序会不 ...
- WPF和Expression Blend开发实例:Loading动画
今天来点实际的,项目中可以真实使用的,一个Loading的动画,最后封装成一个控件,可以直接使用在项目中,先上图: 整个设计比较简单,就是在界面上画18个Path,然后通过动画改变OpacityMas ...
- "Scrum站立会议"浅析
目录 Scrum Scrum Meeting功能及要点 Scrum Meeting点评 Scrum 定义:是一种软件开发流程.它并不是一项技术,这种开发方式的主要驱动核心是人,它采用的是迭代式开发. ...
- v-for & duplicate key bug
v-for & duplicate key bug vue warn & v-for & duplicate key bug <span class="audi ...
- 使用JMeter录制Web应用测试脚本
环境 操作系统:Windows 7 工具:JMeter.Badboy 1. 使用代理录制Web性能测试脚本 使用代理录制脚本来创建测试计划无疑是一个简便的方法,代理所要完成的工作就是录制发往服务器的请 ...