认证授权:IdentityServer4
前言
上一篇文章<学习OIDC>介绍了OIDC协议,本篇开始我们就来具体来学习OIDC的具体实现IdentityServer4 学习。
一、IdentityServer4 是什么?
IdentityServer4是用于ASP.NET Core的OpenID Connect和OAuth 2.0框架。
可以构建(或重新使用)包含登录和注销页面的应用程序,IdentityServer中间件会向其添加必要的协议头,以便客户端应用程序可以使用这些标准协议与其对话。

可以在应用程序中使用以下功能:
- 身份验证即服务
所有应用程序(Web,本机,移动,服务)的集中式登录逻辑和工作流。IdentityServer是OpenID Connect 的官方认证实现
- 单点登录/退出
多种应用程序类型的单点登录(注销)
- API的访问控制
为各种类型的客户端(例如,服务器到服务器,Web应用程序,SPA和本机/移动应用程序)的API发出访问令牌
- 联合网关
支持外部身份提供程序,例如Azure Active Directory,Google,Facebook等。这使您的应用程序免受如何连接到这些外部提供程序的详细信息的影响。
二、简单使用示例
先创建项目目录结构(如下图)

1、IdentityServer 认证服务实现
a) 创建一个空的WebApi项目-cz.IdentityServer,并添加IdentityServer4项目引用:如下图:
Install-Package IdentityServer4
b) 要启用IdentityServer服务,不仅要把 IdentityServer 注册到容器中, 还需要配置一下内容:
- Authorization Server 保护了哪些 API (资源);
哪些客户端 Client(应用) 可以使用这个 Authorization Server;
指定可以使用 Authorization Server 授权的 Users(用户)
创建文件 InMemoryConfig.cs,用于设置以上相关内容:

using IdentityServer4;
using IdentityServer4.Models;
using IdentityServer4.Test;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace cz.IdentityServer
{
public class InMemoryConfig
{
public static IEnumerable<IdentityResource> GetIdentityResourceResources()
{
return new List<IdentityResource>
{
//必须要添加,否则报无效的scope错误
new IdentityResources.OpenId(),
new IdentityResources.Profile()
};
} /// <summary>
/// api资源列表
/// </summary>
/// <returns></returns>
public static IEnumerable<ApiResource> GetApiResources()
{
//可访问的API资源(资源名,资源描述)
return new List<ApiResource>
{
new ApiResource("goods", "Goods Service"),
new ApiResource("order", "Order Service")
};
} /// <summary>
/// 客户端列表
/// </summary>
/// <returns></returns>
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
ClientId = "clientGoods", //访问客户端Id,必须唯一
//使用客户端授权模式,客户端只需要clientid和secrets就可以访问对应的api资源。
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = {
"goods",
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile
},
},
new Client
{
ClientId = "clientOrder",
ClientSecrets = new [] { new Secret("secret".Sha256()) },
//这里使用的是通过用户名密码和ClientCredentials来换取token的方式. ClientCredentials允许Client只使用ClientSecrets来获取token. 这比较适合那种没有用户参与的api动作
AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials,
AllowedScopes = {
"order","goods",
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile
}
}
};
} /// <summary>
/// 指定可以使用 Authorization Server 授权的 Users(用户)
/// </summary>
/// <returns></returns>
public static IEnumerable<TestUser> Users()
{
return new[]
{
new TestUser
{
SubjectId = "",
Username = "cba",
Password = "cba"
},
new TestUser
{
SubjectId = "",
Username = "chaney",
Password = ""
}
};
}
}
}
GetApiResources:这里指定了name和display name, 以后api使用authorization server的时候, 这个name一定要一致
GetClients: 认证客户端列表
Users: 这里的内存用户的类型是TestUser, 只适合学习和测试使用, 实际生产环境中还是需要使用数据库来存储用户信息的, 例如接下来会使用asp.net core identity. TestUser的SubjectId是唯一标识.
在Startup.cs中启用IdentityServer服务
修改StartUp.cs中的ConfigureServices方法
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(InMemoryConfig.GetApiResources())
.AddTestUsers(InMemoryConfig.Users().ToList())
.AddInMemoryIdentityResources(InMemoryConfig.GetIdentityResourceResources())
.AddInMemoryClients(InMemoryConfig.GetClients());
}
修改StartUp.cs中的Configure方法
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseRouting();
//启用IdentityServer
app.UseIdentityServer(); app.UseAuthorization(); app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
运行此项目,打开浏览器访问http://localhost:5600/.well-known/openid-configuration你将会看到IdentityServer的各种元数据信息。

c) 引入QuickStartUI界面
IdentityServer提供了一套UI以使我们能快速的开发具有基本功能的认证/授权界面,下载地址:QuickStartUI
下载后,把QuickStartUI中:wwwroot、Quickstart、Views拷贝到项目中,如下结构:、

修改Statup.cs内容如下:

public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews(); services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddTestUsers(InMemoryConfig.Users().ToList())
.AddInMemoryApiResources(InMemoryConfig.GetApiResources())
.AddInMemoryClients(InMemoryConfig.GetClients());
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseRouting(); app.UseStaticFiles(); app.UseIdentityServer(); app.UseAuthorization(); app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
运行如下效果:

2、IdentityServer 集成Api服务
a)添加web api项目cz.Api.Order,并添加nuget中安装IdentityServer4.AccessTokenValidation ,如下图:
命令:Install-Package IdentityServer4.AccessTokenValidation

b) 修改StartUp.cs文件
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
} public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(); //IdentityServer
services.AddMvcCore()
.AddAuthorization(); //配置IdentityServer
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.RequireHttpsMetadata = false; //是否需要https
options.Authority = $"http://localhost:5600"; //IdentityServer授权路径
options.ApiName = "order"; //需要授权的服务名称
});
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseHttpsRedirection(); app.UseRouting();
//启用Authentication中间件
app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
c) 对cz.Api.Order项目中WebApi添加[Authorize]特性
[Route("identity")]
[ApiController]
[Authorize]
public class IdentityController : ControllerBase
{
}
d) 此时调用该服务时提示401,如下图:

e) 可以通过client信息获取token,然后通过Header传递token 调用weapi


三、总结
通过上面的例子,很简单就实现了WepApi的认证授权效果;主要步骤如下:
- 前往IdentityServer服务中,设置需要请求的ApiResource,Client,User内容
- WebApi服务设置IdentityServerAuthentication地址(对接认证服务)
- 调用WebApi时,先在IdentityServer中根据设置的方式获取access token,再带着access token请求接口才能正常访问
四、后续
IdentityServer包含的内容有很多,准备从多个内容来学习记录使用IdentityServer的功能:SSO(单点登录)、各种授权模式使用、三方账号登录……
最后来实现一个自己的统一身份认证服务
认证授权:IdentityServer4的更多相关文章
- 基于IdentityServer4 实现.NET Core的认证授权
IdentityServer4是什么? IdentityServer4是基于ASP.NET Core实现的认证和授权框架,是对OpenID Connect和OAuth 2.0协议的实现. OpenID ...
- .net core gRPC与IdentityServer4集成认证授权
前言 随着.net core3.0的正式发布,gRPC服务被集成到了VS2019.本文主要演示如何对gRPC的服务进行认证授权. 分析 目前.net core使用最广的认证授权组件是基于OAuth2. ...
- 授权认证(IdentityServer4)
区别 OpenId: Authentication :认证 Oauth: Aurhorize :授权 输入账号密码,QQ确认输入了正确的账号密码可以登录 --->认证 下面需要勾选的复选框(获取 ...
- 一看就懂的IdentityServer4认证授权设计方案
查阅了大多数相关资料,总结设计一个IdentityServer4认证授权方案,我们先看理论,后设计方案. 1.快速理解认证授权 我们先看一下网站发起QQ认证授权,授权通过后获取用户头像,昵称的流程. ...
- Spring Cloud 微服务中搭建 OAuth2.0 认证授权服务
在使用 Spring Cloud 体系来构建微服务的过程中,用户请求是通过网关(ZUUL 或 Spring APIGateway)以 HTTP 协议来传输信息,API 网关将自己注册为 Eureka ...
- .Net Core身份认证:IdentityServer4实现OAuth 2.0 客户端模式 - 简书
原文:.Net Core身份认证:IdentityServer4实现OAuth 2.0 客户端模式 - 简书 一.客户端模式介绍 客户端模式(Client Credentials Grant)是指客户 ...
- 一站式WebAPI与认证授权服务
保护WEBAPI有哪些方法? 微软官方文档推荐了好几个: Azure Active Directory Azure Active Directory B2C (Azure AD B2C)] Ident ...
- 一款基于.NET Core的认证授权解决方案-葫芦藤1.0开源啦
背景 18年公司准备在技术上进行转型,而公司技术团队是互相独立的,新技术的推动阻力很大.我们需要找到一个切入点.公司的项目很多,而各个系统之间又不互通,导致每套系统都有一套登录体系,给员工和客户都带来 ...
- Owin中间件搭建OAuth2.0认证授权服务体会
继两篇转载的Owin搭建OAuth 2.0的文章,使用Owin中间件搭建OAuth2.0认证授权服务器和理解OAuth 2.0之后,我想把最近整理的资料做一下总结. 前两篇主要是介绍概念和一个基本的D ...
随机推荐
- Hive对字段进行urlDecode
最近项目中需要对埋点日志hive表进行分析,并且按一定的规则统计出来满足要求的用户pin.本来以为是一件比较简单的事,结果在查看导出的词表时发现很多带有"%"的明显具有url en ...
- Vue组件注册
全局注册方法 Vue.component('my-component-name', { // ... 选项 ... }) Vue.component('component-a', { /* ... * ...
- 在Springboot中写使用jsp
jsp其实可以看成一种模板语言,在Springboot中我们同样可以使用jsp.我们可以把引入jsp的过程分为三步: 第一步:POM文件加依赖: <!--引入springboot内嵌的tomca ...
- C++socket编程write()、read()简介及与send()、recv()的区别
1. write 函数原型:ssize_t write(int fd, const void*buf,size_t nbytes)write函数将buf中的nbytes字节内容写入文件描述符fd.成功 ...
- 2020-04-13:怎么在日志里排查错误,该用哪些Linux命令
能通过less命令打开文件,通过Shift+G到达文件底部,再通过?+关键字的方式来根据关键来搜索信息. 能通过grep的方式查关键字,具体用法是, grep 关键字 文件名,如果要两次在结果里查找的 ...
- X86汇编——计算斐波那契数列程序(详细注释和流程图说明)
X86汇编实现斐波那契数列 程序说明: 输入斐波那契数列的项数, 然后依次输出斐波那契数列, 输入的项数小于256且为数字, 计算的项数不能超过2^16次方, 输入失败是 不会回显数字 因为存结果是A ...
- Spring Boot自定义错误视图
Spring Boot缺省错误视图解析器 Web应用在处理请求的过程中发生错误是非常常见的情况,SpringBoot中为我们实现了一个错误视图解析器(DefaultErrorViewResolver) ...
- 存储系列之 从ext2到ext3、ext4 的变化与区别
引言:ext3 和 ext4 对 ext2 进行了增强,但是其核心设计并没有发生变化.所以建议先查看上上篇的<存储系列之 Linux ext2 概述 >,有了ext2的基础,看这篇就是so ...
- 大侠稍等!URL 中为何出现奇怪的字符
为什么中文名称的图片打开后网址是一串乱码?为什么好好的短网址复制粘贴就变长了一大长串?罪魁祸首居然是-- 杭州终于出梅了!二狗子看到气象台发布的消息,开心的不得了.杭州的雨从五月底一直下,每天除了雨还 ...
- hdfs学习(二)
一.HDFS文件限额配置 在多人共用HDFS的环境下,配置设置非常重要.特别是在Hadoop处理大量资料的环境,如果没有配额管理,很容易把所有的空间用完造成别人无法存取.Hdfs的配额设定是针对目录而 ...