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 ...
随机推荐
- echarts基本使用与注意事项
npm 安装echarts npm install echarts -D 使用流程 1. 引入echarts,并配置成全局方法 vue2 import * as echarts from 'echar ...
- 5 分钟教你快速掌握 GitHub Actions 自动部署博客
自从 GitHub 宣布 GitHub Actions 在平台上对所有开发人员和存储库可用以来,GitHub Actions 越来越受欢迎.很多第三方平台在生态系统中有速度等限制,将进一步推动开发人员 ...
- Linux磁盘分区-mount挂载
Linux磁盘分区类型 磁盘存储术语CHS head:磁头 磁头数=盘面数 track:磁道 磁道=柱面数 sector:扇区,512bytes cylinder:柱面 1柱面=512*secto ...
- Django基础之Form和ModelForm组件
https://www.cnblogs.com/clschao/articles/10486468.html 1.创建django项目 2.创建py文件 3.导入form from django im ...
- MOSFET, MOS管, 开关管笔记
MOSFET, MOS管, 开关管 MOSFET, Metal-Oxide-Semiconductor Field-Effect Transistor, 金属氧化物半导体场效晶体管 常见封装 电路符号 ...
- CentOS7 安装高版本gcc, g++, gfortran等工具
SCL(Software Collections)是一个CentOS/RHEL Linux平台的软件多版本共存解决方案,为用户提供一种方便.安全地安装和使用应用程序和运行时环境的多个版本的方式. De ...
- 【Java面试】Spring中 BeanFactory和FactoryBean的区别
一个工作了六年多的粉丝,胸有成竹的去京东面试. 然后被Spring里面的一个问题卡住,唉,我和他说,6年啦,Spring都没搞明白? 那怎么去让面试官给你通过呢? 这个问题是: Spring中Bean ...
- 【freertos】009-任务控制
目录 前言 9.1 相对延时 9.1.1 函数原型 9.1.2 函数说明 9.1.3 参考例子 9.2 绝对延时 9.2.1 函数原型 9.2.2 函数说明 9.2.3 参考例子 9.3 获取任务优先 ...
- unittest框架里的常用断言方法:用于检查数据
1.unittest框架里的常用断言方法:用于检查数据. (1)assertEqual(x,y) 检查两个参数类型相同并且值相等.(2)assertTrue(x) 检查唯一的参数值等于True(3)a ...
- python生产exe文件yi以及解释器配置等
原文链接:https://blog.csdn.net/weixin_42691768/article/details/81044666 https://www.cnblogs.com/paulwhw/ ...