IdentityServer4 是一个基于 .NET Core 的 OpenID Connect 实现框架。

基于框架创建可运行的应用,通常还需要多个步骤,添加引用、配置项目、框架初始化、按照一系列步骤启动应用等等。那么,基于 IdentityServer4 创建一个可运行的 OpenID Connect 服务器需要多少行代码呢?

得益于 .net core 提供的项目模版支持,实际上,不需要你写一行代码,只需要执行几个简单的命令就可以了。

1. 准备 IdentityServer4 模版

还记得使用 .net core 的命令行工具 dotnet 创建项目使用的 new 命令吗?如果你希望创建名为 HelloWorld 的项目,那么,创建它的命令如下:

dotnet new console -n HelloWorld

该命令会在当前目录下创建 HelloWorld 子目录。命令执行完成之后,进入这个 HelloWorld 目录中,就可以通过 run 命令来运行了。

>cd HelloWorld
>dotnet run
Hello World!

这个 console 就是通过内置的模版来实现的。当前支持的模版可以通过 list 子命令列出

dotnet new -list

在 dotnet 中,还可以通过 -i 参数来安装新的模版。模版既可以通过一个路径提供,也可以通过一个 nuget_id 来提供。你可能已经想到了,IdentityServer4 就已经提供了一个预定义在 NuGet 中的模版:IdentityServer4.Templates,你可以直接在 NuGet 中找到它:https://www.nuget.org/packages/IdentityServer4.Templates。需要说明的是,同一个项目模版可能存在多个版本,在安装的时候,可以通过在模版名称后面使用两个冒号来分隔特定的版本号,默认情况下,只安装最新的稳定版本。

所以,事情变得简单了。我们需要的就是先在本地安装这个模版,然后,使用这个模版就可以直接创建出完整的 IdentityServer4 项目,然后直接运行。

dotnet new --install IdentityServer4.Templates

NuGet 中的提示是安装特定的版本,现在的最新稳定版本是 3.1.1,所以命令变成了

dotnet new --install IdentityServer4.Templates::3.1.1

在命令的输出中,可以看到已经安装了多个关于 IdentityServer4 的模版

Templates Short Name Language Tags
IdentityServer4 with AdminUI is4admin [C#] Web/IdentityServer4
IdentityServer4 with ASP.NET Core Identity is4aspid [C#] Web/IdentityServer4
IdentityServer4 Empty is4empty [C#] Web/IdentityServer4
IdentityServer4 with Entity Framework Stores is4ef [C#] Web/IdentityServer4
IdentityServer4 with In-Memory Stores and Test Users is4inmem [C#] Web/IdentityServer4
IdentityServer4 Quickstart UI (UI assets only) is4ui [C#] Web/IdentityServer4

这里面最为简单的项目模版就是 IdentityServer4 Empty 了,它简称为 is4empty ,我们下面就使用它来创建项目。

2. 创建第一个 IdentityServer4 项目

直接使用 .net core 的 new 命令来创建项目,我们将创建的项目命名为 IdentityServer

dotnet new is4empty -n IdentityServer

执行之后,会在当前目录下创建 IdentityServer 文件夹,所有的项目文件都位于其中。

3. 启动应用

使用 .net core 的 run 命令来启动项目,可以看到如下输出:

dotnet new is4empty -n IdentityServer
PS C:\temp\is4\IdentityServer> dotnet run
[19:34:49 Information]
Starting host...

[19:34:50 Information] IdentityServer4.Startup
Starting IdentityServer4 version 3.1.0.0

[19:34:50 Information] IdentityServer4.Startup
You are using the in-memory version of the persisted grant store. This will store consent decisions, authorization codes, refrtion.

[19:34:50 Information] IdentityServer4.Startup
Using the default authentication scheme idsrv for IdentityServer

[19:34:50 Debug] IdentityServer4.Startup
Using idsrv as default ASP.NET Core scheme for authentication

[19:34:50 Debug] IdentityServer4.Startup
Using idsrv as default ASP.NET Core scheme for sign-in

[19:34:50 Debug] IdentityServer4.Startup
Using idsrv as default ASP.NET Core scheme for sign-out

[19:34:50 Debug] IdentityServer4.Startup
Using idsrv as default ASP.NET Core scheme for challenge

[19:34:50 Debug] IdentityServer4.Startup
Using idsrv as default ASP.NET Core scheme for forbid

祝贺你!你已经成功创建了第一个可运行的 IdentityServer4 服务器!

4. 访问配置信息

虽然还没有写一行代码,但是,服务器已经在工作了,我们可以通过它的 .well-known 端点来访问服务器的配置信息,在浏览器的地址栏中,输入地址:http://localhost:5000/.well-known/openid-configuration,并回车。应该可以看到如下的响应信息。

{
"issuer": "http://localhost:5000",
"jwks_uri": "http://localhost:5000/.well-known/openid-configuration/jwks",
"authorization_endpoint": "http://localhost:5000/connect/authorize",
"token_endpoint": "http://localhost:5000/connect/token",
"userinfo_endpoint": "http://localhost:5000/connect/userinfo",
"end_session_endpoint": "http://localhost:5000/connect/endsession",
"check_session_iframe": "http://localhost:5000/connect/checksession",
"revocation_endpoint": "http://localhost:5000/connect/revocation",
"introspection_endpoint": "http://localhost:5000/connect/introspect",
"device_authorization_endpoint": "http://localhost:5000/connect/deviceauthorization",
"frontchannel_logout_supported": true,
"frontchannel_logout_session_supported": true,
"backchannel_logout_supported": true,
"backchannel_logout_session_supported": true,
"scopes_supported": [
"openid",
"offline_access"
],
"claims_supported": [
"sub"
],
"grant_types_supported": [
"authorization_code",
"client_credentials",
"refresh_token",
"implicit",
"urn:ietf:params:oauth:grant-type:device_code"
],
"response_types_supported": [
"code",
"token",
"id_token",
"id_token token",
"code id_token",
"code token",
"code id_token token"
],
"response_modes_supported": [
"form_post",
"query",
"fragment"
],
"token_endpoint_auth_methods_supported": [
"client_secret_basic",
"client_secret_post"
],
"id_token_signing_alg_values_supported": [
"RS256"
],
"subject_types_supported": [
"public"
],
"code_challenge_methods_supported": [
"plain",
"S256"
],
"request_parameter_supported": true
}

5. 查看项目代码

5.1 项目文件

项目文件名称为 IdentityServer4.csproj,内容如下:

<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup> <ItemGroup>
<PackageReference Include="IdentityServer4" Version="3.1.0" />
<PackageReference Include="Serilog.AspNetCore" Version="3.2.0" />
<!-- <PackageReference Include="System.Security.Principal.Windows" Version="4.7.0" /> -->
</ItemGroup>
</Project>

主要做了 3 件事:

  • 配置了项目为 Web 应用项目,通过 Sdk 属性指定了 Microsoft.NET.Sdk.Web,目标框架为 .net core 3.1。

  • 添加了对 IdentityServer4 的引用,这就是 IdentityServer4 的实现库

  • 添加了日志库 Serilog.AspNetCore

5.2 Program.cs

这里面相当多的代码是关于 Serilog 日志的配置,关于 Web 站点,只是使用了标准的 Startup 方式启动。

// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.


using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.SystemConsole.Themes;
using System;

namespace IdentityServer
{
public class Program
{
public static int Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("System", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.AspNetCore.Authentication", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}", theme: AnsiConsoleTheme.Literate)
.CreateLogger();

try
{
Log.Information("Starting host...");
CreateHostBuilder(args).Build().Run();
return 0;
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly.");
return 1;
}
finally
{
Log.CloseAndFlush();
}
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.UseSerilog();
});
}
}

5.3 Startup.cs

在 ConfigureServices() 中,最为关键的一行就是添加了 IdentityServer4 服务的支持。

由于这是用于演示的空项目,所以,具体的 OpenID Connect 配置信息来自于一个代码文件 Config,并使用硬编码的方式来用于 IdentityServer

var builder = services.AddIdentityServer()
.AddInMemoryIdentityResources(Config.Ids)
.AddInMemoryApiResources(Config.Apis)
.AddInMemoryClients(Config.Clients);

这个 Config.cs 文件中,还没有对这些信息进行配置。

// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.


using IdentityServer4.Models;
using System.Collections.Generic;

namespace IdentityServer
{
public static class Config
{
public static IEnumerable<IdentityResource> Ids =>
new IdentityResource[]
{
new IdentityResources.OpenId()
};

public static IEnumerable<ApiResource> Apis =>
new ApiResource[]
{ }; public static IEnumerable<Client> Clients =>
new Client[]
{ }; }
}

在 Configure() 中,则启用了 IdentityServer 服务。

app.UseIdentityServer();

完整的代码如下所示:

// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.


using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace IdentityServer
{
public class Startup
{
public IWebHostEnvironment Environment { get; }

public Startup(IWebHostEnvironment environment)
{
Environment = environment;
}

public void ConfigureServices(IServiceCollection services)
{
// uncomment, if you want to add an MVC-based UI
//services.AddControllersWithViews();

var builder = services.AddIdentityServer()
.AddInMemoryIdentityResources(Config.Ids)
.AddInMemoryApiResources(Config.Apis)
.AddInMemoryClients(Config.Clients);

// not recommended for production - you need to store your key material somewhere secure
builder.AddDeveloperSigningCredential();
}

public void Configure(IApplicationBuilder app)
{
if (Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

// uncomment if you want to add MVC
//app.UseStaticFiles();
//app.UseRouting();

app.UseIdentityServer();

// uncomment, if you want to add MVC
//app.UseAuthorization();
//app.UseEndpoints(endpoints =>
//{
// endpoints.MapDefaultControllerRoute();
//});
}
}
}

参考资料

IdentityServer4 快速上手的更多相关文章

  1. 【Python五篇慢慢弹】快速上手学python

    快速上手学python 作者:白宁超 2016年10月4日19:59:39 摘要:python语言俨然不算新技术,七八年前甚至更早已有很多人研习,只是没有现在流行罢了.之所以当下如此盛行,我想肯定是多 ...

  2. 快速上手Unity原生Json库

    现在新版的Unity(印象中是从5.3开始)已经提供了原生的Json库,以前一直使用LitJson,研究了一下Unity用的JsonUtility工具类的使用,发现使用还挺方便的,所以打算把项目中的J ...

  3. [译]:Xamarin.Android开发入门——Hello,Android Multiscreen快速上手

    原文链接:Hello, Android Multiscreen Quickstart. 译文链接:Hello,Android Multiscreen快速上手 本部分介绍利用Xamarin.Androi ...

  4. [译]:Xamarin.Android开发入门——Hello,Android快速上手

    返回索引目录 原文链接:Hello, Android_Quickstart. 译文链接:Xamarin.Android开发入门--Hello,Android快速上手 本部分介绍利用Xamarin开发A ...

  5. 快速上手seajs——简单易用Seajs

    快速上手seajs——简单易用Seajs   原文  http://www.cnblogs.com/xjchenhao/p/4021775.html 主题 SeaJS 简易手册 http://yslo ...

  6. Git版本控制Windows版快速上手

    说到版本控制,之前用过VSS,SVN,Git接触不久,感觉用着还行.写篇博文给大家分享一下使用Git的小经验,让大家对Git快速上手. 说白了Git就是一个控制版本的工具,其实没想象中的那么复杂,咱在 ...

  7. Objective-C快速上手

    最近在开发iOS程序,这篇博文的内容是刚学习Objective-C时做的笔记,力图达到用最短的时间了解OC并使用OC.Objective-C是OS X 和 iOS平台上面的主要编程语言,它是C语言的超 ...

  8. Netron开发快速上手(二):Netron序列化

    Netron是一个C#开源图形库,可以帮助开发人员开发出类似Visio的作图软件.本文继前文”Netron开发快速上手(一)“讨论如何利用Netron里的序列化功能快速保存自己开发的图形对象. 一个用 ...

  9. Netron开发快速上手(一):GraphControl,Shape,Connector和Connection

    版权所有,引用请注明出处:<<http://www.cnblogs.com/dragon/p/5203663.html >> 本文所用示例下载FlowChart.zip 一个用 ...

  10. NHibernate3快速上手教程FluentNHibernate配置与DBHelper

    很多学习NHibernate的新手很容易卡在配置文件这一关,正所谓万事开头难,上手后再配合官方文档就比较容易了. 网上关于配置文件的资料非常多,但由于版本的问题,许多老的教程中都没有明确指出类库的版本 ...

随机推荐

  1. PHP面试,ES

    什么是Elasticsearch? Elasticsearch是一个开源的分布式搜索和分析引擎,用于存储.搜索和分析大量数据.它基于Lucene搜索引擎构建,可以快速地执行全文搜索.结构化查询.分析和 ...

  2. OOP的核心思想

    1. 封装 既是信息封装,把一些信息进行封装成对象,只保留部分接口和方法与外部联系,能有效避免程序间相互依赖,实现代码模块间松藕合 : 2. 继承 子类自动继承父类的属性和方法,继承实现了代码的重用性 ...

  3. Vue3 的 nextTick 函数

    作用: DOM 渲染是异步耗时的, vue2.x 需要等到 DOM 渲染完成之后做某个事情,需要使用 this.$nextTick , vue3.x 则直接提供了 nextTick 这个方法去实现 : ...

  4. Vmware挂载san存储_vSphere 6.x 共享存储LUN丢失分区表修复(精华)

    Vmware挂载san存储_vSphere 6.x 共享存储LUN丢失分区表修复 炎炎夏夜客户机房空调意外故障,前端ESXI物理服务器由于温度过高都自保关机,存储和SAN没有自保关机.上班修复空调后, ...

  5. 基于 KubeSphere 的分级管理实践

    作者:许伟,航天网信研发工程师 K8s 是容器编排和分布式应用部署领域的领导者,在 K8s 环境中,我们只需要关心应用的业务逻辑,减轻了我们服务器网络以及存储等方面的管理负担.对于一个用户而言,K8s ...

  6. C++ 命令行传参 参数使用 坐标参数的转换

    目录 1. 什么是命令行传参 2. 如何传参 3. 应用实例 4. 问题 1. 什么是命令行传参 命令行传参就是在 cmd 命令提示符, 或者 Linux shell 中使用可执行程序时, 可以添加 ...

  7. Redis的发布订阅Pub/Sub

    发布订阅 Redis 发布订阅(publish/subscribe)是一种消息通信模式:发送者(pub)发送消息,订阅者(sub)接收消息. Redis 客户端可以订阅任意数量的频道. 下图展示了频道 ...

  8. ABC 364

    ABC 364 E - Maximum Glutton 给定 \((a_i,b_i),X,Y\), 记 \(k\) 是第一个让 \(\sum_{i=1}^{k} a_i > X\) 或 \(\s ...

  9. Redis的ZSet底层数据结构,ZSet类型全面解析

    文章目录 一.ZSet有序集合类型 1.1 简介 1.2 应用场景 1.3 底层结构 1.4 ZSet常用命令 二.ZSet底层结构详解 2.1 数据结构 2.2 压缩列表ZipList 2.3 跳表 ...

  10. golang中defer的作用

    defer是golang里面一个很有用的语法,但很多人可能都不太清楚它具体应该怎么用.这里记录一下自己学习到的内容. 应用场景 defer一般用于资源释放,当一个资源申请成功后,经常会在后面写一个de ...