叙述

  最近在搞 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 验证服务器的更多相关文章

  1. 坎坷路:ASP.NET Core 1.0 Identity 身份验证(中集)

    上一篇:<坎坷路:ASP.NET 5 Identity 身份验证(上集)> ASP.NET Core 1.0 什么鬼?它是 ASP.NET vNext,也是 ASP.NET 5,以后也可能 ...

  2. 使用asp.net core 3.0 搭建智能小车1

    跟随.net core 3.0 一起发布的System.Device.Gpio 1.0已经可以让我们用熟悉的C#原汁原味的开发莓派上面的GPIO了.并且在 Iot.Device.Bindings这个包 ...

  3. ASP.NET Core 6.0 基于模型验证的数据验证

    1 前言 在程序中,需要进行数据验证的场景经常存在,且数据验证是有必要的.前端进行数据验证,主要是为了减少服务器请求压力,和提高用户体验:后端进行数据验证,主要是为了保证数据的正确性,保证系统的健壮性 ...

  4. .net core 1.0 实现负载多服务器单点登录

    前言 .net core 出来有一时间了,这段时间也一直在做技术准备,目前想做一个单点登录(SSO)系统,在这之前用.net时我用习惯了machineKey ,也顺手在.net core 中尝试了一上 ...

  5. .net core 2.0 登陆权限验证

    首先在Startup的ConfigureServices方法添加一段权限代码 services.AddAuthentication(x=> { x.DefaultAuthenticateSche ...

  6. 用Apache James 3.3.0 搭建个人邮箱服务器

    准备域名 比如域名为example.net,则邮箱格式为test@example.net.在自己的域名管理界面,添加一条A记录(mail.example.net  xxx.xxx.xxx.xxx),指 ...

  7. 使用asp.net core 3.0 搭建智能小车2

    上一篇中我们把基本的运行环境搭建完成了,这一篇中,我们实战通过树莓派B+连接HC-SR04超声波测距传感器,用c# GPIO控制传感器完成距离测定,并将距离显示在网页上. 1.HC-SR04接线 传感 ...

  8. DotNetOpenAuth实践之搭建验证服务器

    系列目录: DotNetOpenAuth实践系列(源码在这里) DotNetOpenAuth是OAuth2的.net版本,利用DotNetOpenAuth我们可以轻松的搭建OAuth2验证服务器,不废 ...

  9. OpenID Connect Core 1.0(一)介绍

    IdentityServer4是基于OpenID Connect and OAuth 2.0框架,OpenID Connect Core 1.0是IdentityServer4最重要的文档 By 道法 ...

随机推荐

  1. python实用工具包

    文本处理 FlashText     大规模关键字搜索利器,据说多余500个关键字时性能会明显优于正则表达式,暂未评测! 调试利器 pysnooper     不需要使用print进行调试

  2. Python--day42--MySQL外键定义及创建

    什么是外键? 外键的创建:constraint 外键名 foregin key ("表1值1",“ 表1值2”) references 表2的名字(“值1”)

  3. 【codeforces 761B】Dasha and friends

    time limit per test2 seconds memory limit per test256 megabytes inputstandard input outputstandard o ...

  4. H3C DHCP中继配置示例

  5. java 类加载器的委托机制

    l 当Java虚拟机要加载一个类时,到底派出哪个类加载器去加载呢? 1.首先当前线程的类加载器去加载线程中的第一个类. 2.如果类A中引用了类B,Java虚拟机将使用加载类A的类装载器来加载类B. 3 ...

  6. Nginx的三种应用场景介绍

    配置虚拟主机 就是在一台服务器启动多个网站. 如何区分不同的网站: 1.域名不同 2.端口不同 1.1. 通过端口区分不同虚拟机 Nginx的配置文件: /usr/local/nginx/conf/n ...

  7. thinter图形开发界面

    tkinter编程步骤 导入Tkinter 创建控件 import thinter 创建主窗口 #win = tkinter.Tk() 设置标题 win.title("xiaoxin&quo ...

  8. Spring Security 学习笔记-securityContext过滤器过滤链学习

    web.xml配置委托代理filter,filter-name默认与filter bean的名字保持一致. <filter> <filter-name>springSecuri ...

  9. Scala中的函数表达式

    最近看Spark的东西,由于之前没有接触过lambda函数表达式,所以搜了点资料,特地纪录在此 Scala中的Lambda表达式 在函数式编程中,函数是基本的构造块.Scala融合了java中的面向对 ...

  10. 牛客wannafly 挑战赛14 B 前缀查询(trie树上dfs序+线段树)

    牛客wannafly 挑战赛14 B 前缀查询(trie树上dfs序+线段树) 链接:https://ac.nowcoder.com/acm/problem/15706 现在需要您来帮忙维护这个名册, ...