.net core 3.0 搭建 IdentityServer4 验证服务器

2024-03-01 17:32

本文主要是介绍.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

          https://www.cnblogs.com/ZaraNet/p/10323400.html

          https://www.cnblogs.com/lihuadeblog/p/12123686.html

 

 

这篇关于.net core 3.0 搭建 IdentityServer4 验证服务器的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/763243

相关文章

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

服务器集群同步时间手记

1.时间服务器配置(必须root用户) (1)检查ntp是否安装 [root@node1 桌面]# rpm -qa|grep ntpntp-4.2.6p5-10.el6.centos.x86_64fontpackages-filesystem-1.41-1.1.el6.noarchntpdate-4.2.6p5-10.el6.centos.x86_64 (2)修改ntp配置文件 [r

poj 1258 Agri-Net(最小生成树模板代码)

感觉用这题来当模板更适合。 题意就是给你邻接矩阵求最小生成树啦。~ prim代码:效率很高。172k...0ms。 #include<stdio.h>#include<algorithm>using namespace std;const int MaxN = 101;const int INF = 0x3f3f3f3f;int g[MaxN][MaxN];int n

搭建Kafka+zookeeper集群调度

前言 硬件环境 172.18.0.5        kafkazk1        Kafka+zookeeper                Kafka Broker集群 172.18.0.6        kafkazk2        Kafka+zookeeper                Kafka Broker集群 172.18.0.7        kafkazk3

4B参数秒杀GPT-3.5:MiniCPM 3.0惊艳登场!

​ 面壁智能 在 AI 的世界里,总有那么几个时刻让人惊叹不已。面壁智能推出的 MiniCPM 3.0,这个仅有4B参数的"小钢炮",正在以惊人的实力挑战着 GPT-3.5 这个曾经的AI巨人。 MiniCPM 3.0 MiniCPM 3.0 MiniCPM 3.0 目前的主要功能有: 长上下文功能:原生支持 32k 上下文长度,性能完美。我们引入了

【IPV6从入门到起飞】5-1 IPV6+Home Assistant(搭建基本环境)

【IPV6从入门到起飞】5-1 IPV6+Home Assistant #搭建基本环境 1 背景2 docker下载 hass3 创建容器4 浏览器访问 hass5 手机APP远程访问hass6 更多玩法 1 背景 既然电脑可以IPV6入站,手机流量可以访问IPV6网络的服务,为什么不在电脑搭建Home Assistant(hass),来控制你的设备呢?@智能家居 @万物互联

如何在Visual Studio中调试.NET源码

今天偶然在看别人代码时,发现在他的代码里使用了Any判断List<T>是否为空。 我一般的做法是先判断是否为null,再判断Count。 看了一下Count的源码如下: 1 [__DynamicallyInvokable]2 public int Count3 {4 [__DynamicallyInvokable]5 get

2、PF-Net点云补全

2、PF-Net 点云补全 PF-Net论文链接:PF-Net PF-Net (Point Fractal Network for 3D Point Cloud Completion)是一种专门为三维点云补全设计的深度学习模型。点云补全实际上和图片补全是一个逻辑,都是采用GAN模型的思想来进行补全,在图片补全中,将部分像素点删除并且标记,然后卷积特征提取预测、判别器判别,来训练模型,生成的像

Linux服务器Java启动脚本

Linux服务器Java启动脚本 1、初版2、优化版本3、常用脚本仓库 本文章介绍了如何在Linux服务器上执行Java并启动jar包, 通常我们会使用nohup直接启动,但是还是需要手动停止然后再次启动, 那如何更优雅的在服务器上启动jar包呢,让我们一起探讨一下吧。 1、初版 第一个版本是常用的做法,直接使用nohup后台启动jar包, 并将日志输出到当前文件夹n

pico2 开发环境搭建-基于ubuntu

pico2 开发环境搭建-基于ubuntu 安装编译工具链下载sdk 和example编译example 安装编译工具链 sudo apt install cmake gcc-arm-none-eabi libnewlib-arm-none-eabi libstdc++-arm-none-eabi-newlib 注意cmake的版本,需要在3.17 以上 下载sdk 和ex