.net core 3.0 搭建 IdentityServer4 验证服务器
叙述
最近在搞 IdentityServer4 API接口认证部分,由于之前没有接触过 IdentityServer4 于是在网上一顿搜搜搜,由于自己技术水平也有限,看了好几篇文章才搞懂,想通过博客方式整理一下同时也希望帮到刚了解 IdentityServer4 的小伙伴。
在搭建 IdentityServer4 之前,需要了解以下几个概念。
OpenId
OpenID 是一个以用户为中心的数字身份识别框架,它具有开放、分散性。OpenID 的创建基于这样一个概念:我们可以通过 URI (又叫 URL 或网站地址)来认证一个网站的唯一身份,同理,我们也可以通过这种方式来作为用户的身份认证。
简而言之:OpenId用于身份认证(Authentication)。
OAuth 2.0
OAuth(开放授权)是一个开放标准,目前的版本是2.0。允许用户授权第三方移动应用访问他们存储在其他服务商上存储的私密的资源(如照片,视频,联系人列表),而无需将用户名和密码提供给第三方应用。
OAuth允许用户提供一个令牌而不是用户名和密码来访问他们存放在特定服务商上的数据。每一个令牌授权一个特定的网站内访问特定的资源(例如仅仅是某一相册中的视频)。这样,OAuth可以允许用户授权第三方网站访问他们存储在另外服务提供者的某些特定信息,而非所有内容。
OAuth是OpenID的一个补充,但是完全不同的服务。
简而言之:OAuth2.0 用于授权(Authorization)。
OpenId Connect
OpenID Connect 1.0 是基于OAuth 2.0协议之上的简单身份层,它允许客户端根据授权服务器的认证结果最终确认终端用户的身份,以及获取基本的用户信息;它支持包括Web、移动、JavaScript在内的所有客户端类型去请求和接收终端用户信息和身份认证会话信息;它是可扩展的协议,允许你使用某些可选功能,如身份数据加密、OpenID提供商发现、会话管理等。
简而言之:OpenId Connect = OIDC = Authentication + Authorization + OAuth2.0。
开始搭建 IdentityServer4
1.首先我们需要创建一个API项目来搭建 IdentityServer4 认证服务器。

2.通过 Nuget 安装 IdentityServer4 。

3.删除 .net core webapi 自带的 WeatherForecast 控制器和 WeatherForecast 类。(当然不是必须删除)
4.创建 ApiConfig 类用于配置 IdentityServer4 的参数。
using IdentityServer4.Models;
using System.Collections.Generic; namespace IdentityServer
{
public class ApiConfig
{
/// <summary>
/// 这个ApiResource参数就是我们Api
/// </summary>
/// <returns></returns>
public static IEnumerable<ApiResource> GetSoluction()
{
return new[]
{
new ApiResource("api1", "MY API")
};
}
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
ClientId = "Client",
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets = {
new Secret("secret".Sha256()),
},
AllowedScopes = {"api1"}
}
};
}
}
}
5.在 Startup.cs 中注入 IdentityServer 服务并使用中间件。
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentityServer()
.AddInMemoryApiResources(ApiConfig.GetSoluction())
.AddInMemoryClients(ApiConfig.GetClients())
.AddDeveloperSigningCredential(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//添加认证中间件
app.UseIdentityServer();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
6. F5运行项目,并将路径修改为: http://localhost:55320/.well-known/openid-configuration

首次启动时,IdentityServer将为您创建一个开发人员签名密钥,它是一个名为的文件tempkey.rsa。您不必将该文件检入源代码管理中,如果该文件不存在,将重新创建该文件。
7.用 Postman 测试并获取 AccessToken,如下图所示,在 Post 请求中传入,认证类型,client_id 以及 client_secret 即可获取 AccessToken 。

8.创建个 API 项目用于验证 IdentityServer4 。

9.添加名为 Identity 的控制器。


using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq; namespace Api.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class IdentityController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
}
}
}
10.通过 NuGet 安装 IdentityServer4.AccessTokenValidation 。

11. 在 Startup.cs 中加入 identityServer 验证。
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore()
.AddAuthorization(); services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:55320";
options.RequireHttpsMetadata = false; options.ApiName = "api1";
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0); } // 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.UseAuthentication(); //认证服务
app.UseAuthorization(); //使用授权服务 app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
12.同时启动 Api 项目和 Identity 验证服务器。

13.使用 PostMan 进行验证。

源码:
链接: https://pan.baidu.com/s/17ZZqWZi4nCDKEO4o7dLafA
提取码: t8hb
总结:
本文只是初步搭建 IdentityServer4 验证服务器,并没有更深入的探索,如果想有更深入了解的小伙伴可以参考以下链接。
参考:
https://www.cnblogs.com/sheng-jie/p/9430920.html
https://www.cnblogs.com/yilezhu/p/9315644.html
.net core 3.0 搭建 IdentityServer4 验证服务器的更多相关文章
- 坎坷路:ASP.NET Core 1.0 Identity 身份验证(中集)
上一篇:<坎坷路:ASP.NET 5 Identity 身份验证(上集)> ASP.NET Core 1.0 什么鬼?它是 ASP.NET vNext,也是 ASP.NET 5,以后也可能 ...
- 使用asp.net core 3.0 搭建智能小车1
跟随.net core 3.0 一起发布的System.Device.Gpio 1.0已经可以让我们用熟悉的C#原汁原味的开发莓派上面的GPIO了.并且在 Iot.Device.Bindings这个包 ...
- ASP.NET Core 6.0 基于模型验证的数据验证
1 前言 在程序中,需要进行数据验证的场景经常存在,且数据验证是有必要的.前端进行数据验证,主要是为了减少服务器请求压力,和提高用户体验:后端进行数据验证,主要是为了保证数据的正确性,保证系统的健壮性 ...
- .net core 1.0 实现负载多服务器单点登录
前言 .net core 出来有一时间了,这段时间也一直在做技术准备,目前想做一个单点登录(SSO)系统,在这之前用.net时我用习惯了machineKey ,也顺手在.net core 中尝试了一上 ...
- .net core 2.0 登陆权限验证
首先在Startup的ConfigureServices方法添加一段权限代码 services.AddAuthentication(x=> { x.DefaultAuthenticateSche ...
- 用Apache James 3.3.0 搭建个人邮箱服务器
准备域名 比如域名为example.net,则邮箱格式为test@example.net.在自己的域名管理界面,添加一条A记录(mail.example.net xxx.xxx.xxx.xxx),指 ...
- 使用asp.net core 3.0 搭建智能小车2
上一篇中我们把基本的运行环境搭建完成了,这一篇中,我们实战通过树莓派B+连接HC-SR04超声波测距传感器,用c# GPIO控制传感器完成距离测定,并将距离显示在网页上. 1.HC-SR04接线 传感 ...
- DotNetOpenAuth实践之搭建验证服务器
系列目录: DotNetOpenAuth实践系列(源码在这里) DotNetOpenAuth是OAuth2的.net版本,利用DotNetOpenAuth我们可以轻松的搭建OAuth2验证服务器,不废 ...
- OpenID Connect Core 1.0(一)介绍
IdentityServer4是基于OpenID Connect and OAuth 2.0框架,OpenID Connect Core 1.0是IdentityServer4最重要的文档 By 道法 ...
随机推荐
- g++ 编译单个文件和多个文件
转载:https://www.cnblogs.com/battlescars/p/cpp_linux_gcc.html 1.单个源文件生成可执行程序 下面是一个保存在文件 helloworld.cpp ...
- hdu 1255 覆盖的面积 (Bruceforce)
Problem - 1255 暴力统计覆盖超过一次的区域.1y. 代码如下: #include <cstdio> #include <cstring> #include < ...
- spring boot与activiti集成实战 转
为什么80%的码农都做不了架构师?>>> 这是原作者的博客地址 http://wiselyman.iteye.com/blog/2285223 代码格式混乱,我修正了一下.项目源码在 ...
- win2d 渐变颜色
本文告诉大家如何在 win2d 使用渐变颜色 线条渐变 在 UWP 的 Win2d 使用渐变颜色需要 CanvasLinearGradientBrush 做颜色,本文告诉大家如何在 win2d 使用 ...
- ASP.NET MVC 实现页落网资源分享网站+充值管理+后台管理(10)之素材管理
源码下载地址:http://www.yealuo.com/Sccnn/Detail?KeyValue=c891ffae-7441-4afb-9a75-c5fe000e3d1c 素材管理模块也是我们这个 ...
- CSS选择器权重计算规则
从CSS代码存放位置看权重优先级:内嵌样式 > 内部样式表 > 外联样式表.其实这个基本可以忽视之,大部分情况下CSS代码都是使用外联样式表. 从样式选择器看权重优先级:important ...
- dotnet 通过 WMI 获取指定进程的输入命令行
本文告诉大家如何使用 WMI 通过 Process 获取这个进程传入的命令行 使用下面代码,使用 Win32_Process 拿到所有的进程,通过 WHERE 判断当前的进程,然后拿到进程传入的命令 ...
- 2018-10-18-WPF-跨线程-UI-的方法
title author date CreateTime categories WPF 跨线程 UI 的方法 lindexi 2018-10-18 10:25:28 +0800 2018-10-18 ...
- Perl 的内置变量$|
$|是perl的内置变量,默认情况下是0,如果设置为非0的话,表示当前的输出不经过缓存立刻输出.相当于c语言的fflush()函数,立即刷新缓冲区. 比如你print或者write一个文件,实际是需要 ...
- git之本地篇(用tortoisegit操作)
下载: git:https://git-scm.com/downloads tortoisegit(小乌龟):https://tortoisegit.org/ ortoisegit中文语言包 v2.9 ...