.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 道法 ...
随机推荐
- HDU 2546 01背包问题
这里5元是个什么意思呢.差不多就是特殊情况了. 就是说最贵的那个东西先不买.并且最后要留下5元去买那个最贵的. 也就是说对现在金钱-5 拿剩下的钱去对减去最贵的商品后的商品dp.看这些剩下的钱能买多少 ...
- BERT的通俗理解 预训练模型 微调
1.预训练模型 BERT是一个预训练的模型,那么什么是预训练呢?举例子进行简单的介绍 假设已有A训练集,先用A对网络进行预训练,在A任务上学会网络参数,然后保存以备后用,当来一个新 ...
- Hammersley-Clifford定理证明
Proof of Hammersley-Clifford TheoremProof of Hammersley-Clifford Theorem依赖知识定义1定义2证明过程反向证明(吉布斯分布=> ...
- Python--day27--几个内置方法:__repr__()/__str__()/__del__()/__call__()/__getitem__/__setitem/delitem/__new__/__eq__/__hash__
repr方法() 双下方法__str__: 打印对象就相当于打印对象.__str__ __repr__(): __repr__是__str__的备胎,没有__str__的时候,就调用__repr__: ...
- [转载] iptables 防火墙设置
http://hongwei.im/iptables-setting-for-ubuntu-1304/ Iptables是一个防火墙,所有的Ubuntu官方发行版(Ubuntu,Kubuntu,Xub ...
- Spring与C3p0连接数据库对事务操作
maven包: <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncodin ...
- 移动端遇到的bug (长期更新)
移动端遇到的bug border-radius和transform在一起的bug 当父级设置了border-radius+overflow:hidden的时候,圆角是可以包住子级的,这是个很常见的场景 ...
- Java发送邮件Demo
就是个Demo,有使用Spring的东西 package xxxxxxx.common.utils; import org.springframework.mail.javamail.JavaMail ...
- 【9103】求n的累加和
Time Limit: 10 second Memory Limit: 2 MB 问题描述 用高精度方法,求s=1+2+3+...+n的精确值(n以一般整数输入) Input 文件输入仅一行,输入n ...
- P1073 奇数还是偶数
题目描述 给你 \(N(1 \le N \le 1000)\) 个数,你需要判断每个数是奇数还是偶数. 输入格式 输入的第一行包含一个整数 \(N(1 \le N \le 1000)\) . 接下来 ...