Identity Server 4客户端认证控制访问API
项目源码:
链接:https://pan.baidu.com/s/1H3Y0ct8xgfVkgq4XsniqFA
提取码:nzl3
一、说明
我们将定义一个api和要访问它的客户端,客户端将在identityser上请求访问令牌,并使用访问令牌调用api
二、项目结构与准备
1、创建项目QuickStartIdentityServer4的asp.net 3.1项目,端口号5001,NuGet: IdentityServer4
2、创建项目API的asp.net 3.1项目,端口号5000,NuGet: Microsoft.AspNetCore.Authentication.JwtBearer
3、创建项目Client控制台项目(sp.net 3.1),模拟客户端请求,NuGet: IdentityModel

三、QuickStartIdentityServer4项目编码
1、在QuickStartIdentityServer4项目中添加Config.cs文件
public static class Config
{
// 定义api范围
public static IEnumerable<ApiScope> ApiScopes => new []
{
new ApiScope
{
Name="sample_api", // 范围名称,自定义
DisplayName="Sample API" // 范围显示名称,自定义
}
}; // 定义客户端
public static IEnumerable<Client> Clients => new[]
{
new Client
{
ClientId="sample_client", // 客户端id
ClientSecrets =
{
new Secret("sample_client_secret".Sha256()) // 客户端秘钥 },
AllowedGrantTypes=GrantTypes.ClientCredentials, //授权类型为客户端
AllowedScopes={ "sample_api" } // 设置该客户端允许访问的api范围
}
}; }
2、在QuickStartIdentityServer4项目中Startup.cs文件添加配置
public void ConfigureServices(IServiceCollection services)
{
var builder=services.AddIdentityServer();
builder.AddDeveloperSigningCredential();
builder.AddInMemoryApiScopes(Config.ApiScopes);
builder.AddInMemoryClients(Config.Clients);
}
3、访问http://localhost:5001/.well-known/openid-configuration

4、访问http://localhost:5001/connect/token即可拿到令牌token

该token是基于jwt,我们可以在jwt官网进行查看验证,如图

四、API项目编码
1、Startup.cs文件配置
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(); // 添加JWT认证方案
services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", option => {
// OIDC服务地址
option.Authority = "http://localhost:5001";
// 不使用Https
option.RequireHttpsMetadata = false;
// 设置JWT的验证参数
option.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
{
// 因为使用的是api范围访问,该参数需设置false
ValidateAudience=false
}; });
// 添加api授权策略
services.AddAuthorization(options => {
// "ApiScope"为策略名称
options.AddPolicy("ApiScope", builder =>
{
builder.RequireAuthenticatedUser();
// 鉴定claim是否存在
builder.RequireClaim("scope", "sample_api");
}); }); } // 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();
// 设置全局策略,应用于所有api
//endpoints.MapControllers().RequireAuthorization("ApiScope");
});
}
2、添加控制器IdentityServerController并增加授权
[Route("IdentityServer")]
[Authorize("ApiScope")]
public class IdentityServerController : ControllerBase
{
public IActionResult Get()
{
return new JsonResult(from claim in User.Claims select new { claim.Type,claim.Value });
}
}
3、拿到token并请求api

五、Client项目模拟客户端请求
internal class Program
{
static async Task Main(string[] args)
{
var client = new HttpClient();
var disco = await client.GetDiscoveryDocumentAsync("http://localhost:5001");
if (disco.IsError)
{
Console.WriteLine(disco.Error);
return;
} var tokenResponse = await client.RequestClientCredentialsTokenAsync(
new ClientCredentialsTokenRequest
{
Address= disco.TokenEndpoint,
ClientId= "sample_client",
ClientSecret= "sample_client_secret"
}
); if(tokenResponse.IsError)
{
Console.WriteLine(tokenResponse.Error);
return;
} Console.WriteLine(tokenResponse.Json); var apiClient = new HttpClient();
apiClient.SetBearerToken(tokenResponse.AccessToken); var response = await apiClient.PostAsync("http://localhost:5000/IdentityServer", null);
if (!response.IsSuccessStatusCode)
{
Console.WriteLine(response.StatusCode);
}
else
{
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(JArray.Parse(content));
} Console.ReadKey();
}
}
项目运行效果如图

学习链接地址:https://www.cnblogs.com/stulzq/p/7495129.html
Identity Server 4客户端认证控制访问API的更多相关文章
- Identity Server 4资源拥有者密码认证控制访问API
基于上一篇文章中的代码进行继续延伸,只需要小小的改动即可,不明白的地方可以先看看本人上一篇文章及源码: Identity Server 4客户端认证控制访问API 一.QuickStartIdenti ...
- IdentityServer4[3]:使用客户端认证控制API访问(客户端授权模式)
使用客户端认证控制API访问(客户端授权模式) 场景描述 使用IdentityServer保护API的最基本场景. 我们定义一个API和要访问API的客户端.客户端从IdentityServer请求A ...
- IdentityServer4(7)- 使用客户端认证控制API访问(客户端授权模式)
一.前言 本文已更新到 .NET Core 2.2 本文包括后续的Demo都会放在github:https://github.com/stulzq/IdentityServer4.Samples (Q ...
- k8s使用自定义证书将客户端认证接入到API Server
自定义证书使用kubectl认证接入API Serverkubeconfig是API Server的客户端连入API Server时使用的认证格式的客户端配置文件.使用kubectl config v ...
- SQL Server新增用户并控制访问权限设置。
新增用户: 一.进入数据库:[安全性]—>[登录名]—>[新建登录名] 二.在常规选项卡中.如图所示,创建登录名.注意设置默认的数据库. 三.在[用户映射]下设置该用户所能访问的数据库.并 ...
- Identity Server 4使用OpenID Connect添加用户身份验证(三)
一.说明 基于上一篇文章中的代码进行继续延伸,只需要小小的改动即可,不明白的地方可以先看看本人上一篇文章及源码: Identity Server 4资源拥有者密码认证控制访问API(二) GitHub ...
- Identity Server 4 从入门到落地(三)—— 创建Web客户端
书接上回,我们已经搭建好了基于Identity Server 4的认证服务和管理应用(如果还没有搭建,参看本系列前两部分,相关代码可以从github下载:https://github.com/zhen ...
- Identity Server 4 从入门到落地(四)—— 创建Web Api
前面的部分: Identity Server 4 从入门到落地(一)-- 从IdentityServer4.Admin开始 Identity Server 4 从入门到落地(二)-- 理解授权码模式 ...
- Asp.Net Core: Swagger 与 Identity Server 4
Swagger不用多说,可以自动生成Web Api的接口文档和客户端调用代码,方便开发人员进行测试.通常我们只需要几行代码就可以实现这个功能: ... builder.Services.AddSwag ...
随机推荐
- YARN线上动态资源调优
背景 线上Hadoop集群资源严重不足,可能存在添加磁盘,添加CPU,添加节点的操作,那么在添加这些硬件资源之后,我们的集群是不能立马就利用上这些资源的,需要修改集群Yarn资源配置,然后使其生效. ...
- 配置Docker镜像源为国内镜像源
镜像加速 /etc/docker/daemon.json 没有这个文件 创建这个文件 vi /etc/docker/daemon.json 按 i 进行插入 { "registry-mirr ...
- Keepalived入门学习
一个执着于技术的公众号 Keepalived简介 Keepalived 是使用C语言编写的路由热备软件,该项目软件起初是专门为LVS负载均衡设计的,用来管理并监控LVS集群系统中各个服务节点的状态,后 ...
- 10 分钟看懂 Docker 和 K8S!
2010年,几个搞IT的年轻人,在美国旧金山成立了一家名叫"dotCloud"的公司. 这家公司主要提供基于PaaS的云计算技术服务.具体来说,是和LXC有关的容器技术. LXC, ...
- 查重工具Jplag的使用
目录 前言 一.Jplag是什么? 二.使用步骤 1.下载包 2.java环境配置 3.如何使用 三.总结 前言 说明一下本文章针对最新版本Jplag3.0使用JplagAPI 一.Jplag是什么? ...
- range内部代码
def my_range(a, b=None, c=1): if not b: b = a a = 0 while a < b: yield a a += c
- 438. Find All Anagrams in a String - LeetCode
Question 438. Find All Anagrams in a String Solution 题目大意:给两个字符串,s和p,求p在s中出现的位置,p串中的字符无序,ab=ba 思路:起初 ...
- veeambackup通过虚拟机还原系统文件操作说明
如何从 VeeamBackup Replication 从备份中提取文件恢复到本地.当我们的服务器中误操作删除了一些文件特别是共享文件,文件被删除后往往都是几个小时或者几天后才被发现.特别是文件服务器 ...
- 目标检测复习之YOLO系列
目标检测之YOLO系列 YOLOV1: blogs1: YOLOv1算法理解 blogs2: <机器爱学习>YOLO v1深入理解 网络结构 激活函数(leaky rectified li ...
- python自动将新生成的报告作为附件发送并进行封装
发送报告作为自动化部署来讲是一个重要的环节,废话不多说直接上代码吧,如果想更细致的了解内容查阅本博主上篇基本发送文章 特别叮嘱一下:SMTP协议默认端口25,qq邮箱SMTP服务器端口是465 别出丑 ...