二、identityserver4保护api,并使用控制台应用程序访问

2024-03-04 07:18

本文主要是介绍二、identityserver4保护api,并使用控制台应用程序访问,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、创建webapi项目

 (一)分别创建2个webapi项目,分别是3.1(3.0)版本和2.2(2.1)版本。

  先在3.1版本中做测试

  1、将Core3.1API应用程序配置URL为http://localhost:5001

  2、在打开Properties→launchSettings.json配置文件将iis相关配置信息删除。

  删除后的launchSettings.json

{"$schema": "http://json.schemastore.org/launchsettings.json","profiles": {    "WebApi3.x": {"commandName": "Project","launchBrowser": true,"launchUrl": "weatherforecast","applicationUrl": "http://localhost:5001","environmentVariables": {"ASPNETCORE_ENVIRONMENT": "Development"}}}
}

3、将创建项目时默认添加的WeatherForecastController进行代码修改。

在控制器上方添加 [Authorize]特性,用于授权测试。

[ApiController][Route("[controller]")][Authorize]public class WeatherForecastController : ControllerBase{private static readonly string[] Summaries = new[]{"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"};private readonly ILogger<WeatherForecastController> _logger;public WeatherForecastController(ILogger<WeatherForecastController> logger){_logger = logger;}[HttpGet]public IEnumerable<WeatherForecast> Get(){var rng = new Random();return Enumerable.Range(1, 5).Select(index => new WeatherForecast{Date = DateTime.Now.AddDays(index),TemperatureC = rng.Next(-20, 55),Summary = Summaries[rng.Next(Summaries.Length)]}).ToArray();}}

4、在Nuget中添加Microsoft.AspNetCore.Authentication.JwtBearer包

5、最后一步是将身份验证服务添加到DI(依赖注入),并将身份验证中间件添加到管道。这些将:

  • 验证传入令牌以确保它来自受信任的发行者
  • 验证令牌是否可以与此API一起使用

修改Startup文件

 public class Startup{public Startup(IConfiguration configuration){Configuration = configuration;}public IConfiguration Configuration { get; }public void ConfigureServices(IServiceCollection services){services.AddControllers();//将身份验证服务添加到DI并配置Bearer为默认方案。services.AddAuthentication("Bearer").AddJwtBearer("Bearer", options =>{//配置id4授权服务器Urloptions.Authority = "http://localhost:5000";options.RequireHttpsMetadata = false;//设置当前webapi项目的资源名称为api1options.Audience = "api1";});}public void Configure(IApplicationBuilder app, IWebHostEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}app.UseHttpsRedirection();app.UseRouting();//将身份验证中间件添加到管道中,以便对主机的每次调用都将自动执行身份验证。app.UseAuthentication();//添加了授权中间件,以确保匿名客户端无法访问我们的API端点。app.UseAuthorization();app.UseEndpoints(endpoints =>{endpoints.MapControllers();});}}

http://localhost:5001/identity在浏览器上导航至控制器应返回401状态代码。这意味着您的API需要凭据,并且现在受IdentityServer保护。 

 二、创建控制台客户端,用于API资源访问

 1、Nuget安装IdentityModel库

2、修改Program.cs文件

class Program{static async Task Main(string[] args){// IdentityModel包括一个与发现端点一起使用的客户端库。这样,您只需要知IdentityServer的基地址-可以从元数据中读取实际的端点地址。http://localhost:5000identityserver4的Url地址var client = new HttpClient();var disco = await client.GetDiscoveryDocumentAsync("http://localhost:5000");if (disco.IsError){Console.WriteLine(disco.Error);return;}//接下来,您可以使用发现文档中的信息向IdentityServer请求令牌以访问api1var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest{Address = disco.TokenEndpoint,ClientId = "client",//Secret在id4项目中Config.cs文件中配置的AllowedGrantTypes = GrantTypes.ClientCredentials客户端中的ClientSecretsClientSecret = "511536EF-F270-4058-80CA-1C89C192F69A",Scope = "api1"});if (tokenResponse.IsError){Console.WriteLine(tokenResponse.Error);return;}Console.WriteLine(tokenResponse.Json);//要将访问令牌发送到API。这是使用SetBearerToken扩展方法完,设置HTTP授权标头:var clientapi = new HttpClient();clientapi.SetBearerToken(tokenResponse.AccessToken);//访问webapi资源地址var response = await clientapi.GetAsync("http://localhost:5001/WeatherForecast");if (!response.IsSuccessStatusCode){Console.WriteLine(response.StatusCode);}else{var content = await response.Content.ReadAsStringAsync();Console.WriteLine(JArray.Parse(content));}Console.ReadKey();}}

3、先后运行id4项目、webapi项目和客户端项目

客户端项目中打印出webapi项目中WeatherForecast控制器返回的api资源。

Core3.x测试完毕。接下来我们测试2.x版本的webapi保护

三、创建Core2.xwepi项目

1、将创建项目时默认添加的WeatherForecastController进行代码修改。

在控制器上方添加 [Authorize]特性,用于授权测试。

 [Route("api/[controller]")][ApiController][Authorize]public class ValuesController : ControllerBase{// GET api/values[HttpGet]public ActionResult<IEnumerable<string>> Get(){return new string[] { "value1", "value2" };}// GET api/values/5[HttpGet("{id}")]public ActionResult<string> Get(int id){return "value";}// POST api/values[HttpPost]public void Post([FromBody] string value){}// PUT api/values/5[HttpPut("{id}")]public void Put(int id, [FromBody] string value){}// DELETE api/values/5[HttpDelete("{id}")]public void Delete(int id){}}

2、修改Startup.cs文件

public class Startup{public Startup(IConfiguration configuration){Configuration = configuration;}public IConfiguration Configuration { get; }// This method gets called by the runtime. Use this method to add services to the container.public void ConfigureServices(IServiceCollection services){services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);//添加认证services.AddMvcCore().AddAuthorization().AddJsonFormatters();services.AddAuthentication("Bearer").AddJwtBearer("Bearer", options =>{options.Authority = "http://localhost:5000";options.RequireHttpsMetadata = false;options.Audience = "api2";});}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IHostingEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}else{app.UseHsts();}//添加认证中间件app.UseAuthentication();app.UseHttpsRedirection();app.UseMvc();}}

注意:2.x版本不需要像3.x版本一样添加Microsoft.AspNetCore.Authentication.JwtBearer依赖库

3、在打开Properties→launchSettings.json配置文件将iis相关配置信息删除。

  删除后的launchSettings.json

{"$schema": "http://json.schemastore.org/launchsettings.json","profiles": {   "WebApi2.x": {"commandName": "Project","launchBrowser": true,"launchUrl": "api/values","applicationUrl": "http://localhost:5002","environmentVariables": {"ASPNETCORE_ENVIRONMENT": "Development"}}}
}

4、在id4项目的Config.cs文件中添加ApiResource

  public static IEnumerable<ApiResource> Apis =>new ApiResource[]{new ApiResource("api1", "My API #1"),new ApiResource("api2", "My API #2")};

5、将client客户端AllowedScopes修改为api2。

 new Client{ClientId = "client",ClientName = "Client Credentials Client",AllowedGrantTypes = GrantTypes.ClientCredentials,ClientSecrets = { new Secret("511536EF-F270-4058-80CA-1C89C192F69A".Sha256()) },AllowedScopes = { "api2" }},

6、修改ConsoleClient客户端Program.cs文件

class Program{static async Task Main(string[] args){// IdentityModel包括一个与发现端点一起使用的客户端库。这样,您只需要知IdentityServer的基地址-可以从元数据中读取实际的端点地址。http://localhost:5000identityserver4的Url地址var client = new HttpClient();var disco = await client.GetDiscoveryDocumentAsync("http://localhost:5000");if (disco.IsError){Console.WriteLine(disco.Error);return;}//接下来,您可以使用发现文档中的信息向IdentityServer请求令牌以访问api1var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest{Address = disco.TokenEndpoint,ClientId = "client",//Secret在id4项目中Config.cs文件中配置的AllowedGrantTypes = GrantTypes.ClientCredentials客户端中的ClientSecretsClientSecret = "511536EF-F270-4058-80CA-1C89C192F69A",//将原来的api1修改为 api2Scope = "api2"});if (tokenResponse.IsError){Console.WriteLine(tokenResponse.Error);return;}Console.WriteLine(tokenResponse.Json);//要将访问令牌发送到API。这是使用SetBearerToken扩展方法完,设置HTTP授权标头:var clientapi = new HttpClient();clientapi.SetBearerToken(tokenResponse.AccessToken);//var response = await clientapi.GetAsync("http://localhost:5001/WeatherForecast");//修改api请求地址var response = await clientapi.GetAsync("http://localhost:5002/api/Values");if (!response.IsSuccessStatusCode){Console.WriteLine(response.StatusCode);}else{var content = await response.Content.ReadAsStringAsync();Console.WriteLine(JArray.Parse(content));}Console.ReadKey();}}

7、依次运行id4项目、core2.1webapi项目和控制台客户端项目

正确的获取到了core2.x被保护资源。

四、小结

保护Core3.x与2.x的区别就在与Startup文件的配置上。

1、core3.x需要添加Microsoft.AspNetCore.Authentication.JwtBearer包依赖 ,2.x则不需要。

2、core3.x webapi项目 Startup添加文件配置

//ConfigureServices方法中添加
//将身份验证服务添加到DI并配置Bearer为默认方案。services.AddAuthentication("Bearer").AddJwtBearer("Bearer", options =>{//配置id4授权服务器Urloptions.Authority = "http://localhost:5000";options.RequireHttpsMetadata = false;//设置当前webapi项目的资源名称为api1options.Audience = "api1";});
//Configure方法中添加app.UseAuthentication();app.UseAuthorization();

3、core2.x webapi项目 Startup添加文件配置

//ConfigureServices方法中添加
//添加认证services.AddMvcCore().AddAuthorization().AddJsonFormatters();services.AddAuthentication("Bearer").AddJwtBearer("Bearer", options =>{options.Authority = "http://localhost:5000";options.RequireHttpsMetadata = false;options.Audience = "api2";});
//Configure方法中添加//添加认证中间件
app.UseAuthentication();

一、identityerver4Demo项目建立

这篇关于二、identityserver4保护api,并使用控制台应用程序访问的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

sky-take-out项目中Redis的使用示例详解

《sky-take-out项目中Redis的使用示例详解》SpringCache是Spring的缓存抽象层,通过注解简化缓存管理,支持Redis等提供者,适用于方法结果缓存、更新和删除操作,但无法实现... 目录Spring Cache主要特性核心注解1.@Cacheable2.@CachePut3.@Ca

C#下Newtonsoft.Json的具体使用

《C#下Newtonsoft.Json的具体使用》Newtonsoft.Json是一个非常流行的C#JSON序列化和反序列化库,它可以方便地将C#对象转换为JSON格式,或者将JSON数据解析为C#对... 目录安装 Newtonsoft.json基本用法1. 序列化 C# 对象为 JSON2. 反序列化

RabbitMQ 延时队列插件安装与使用示例详解(基于 Delayed Message Plugin)

《RabbitMQ延时队列插件安装与使用示例详解(基于DelayedMessagePlugin)》本文详解RabbitMQ通过安装rabbitmq_delayed_message_exchan... 目录 一、什么是 RabbitMQ 延时队列? 二、安装前准备✅ RabbitMQ 环境要求 三、安装延时队

Python ORM神器之SQLAlchemy基本使用完全指南

《PythonORM神器之SQLAlchemy基本使用完全指南》SQLAlchemy是Python主流ORM框架,通过对象化方式简化数据库操作,支持多数据库,提供引擎、会话、模型等核心组件,实现事务... 目录一、什么是SQLAlchemy?二、安装SQLAlchemy三、核心概念1. Engine(引擎)

Java Stream 并行流简介、使用与注意事项小结

《JavaStream并行流简介、使用与注意事项小结》Java8并行流基于StreamAPI,利用多核CPU提升计算密集型任务效率,但需注意线程安全、顺序不确定及线程池管理,可通过自定义线程池与C... 目录1. 并行流简介​特点:​2. 并行流的简单使用​示例:并行流的基本使用​3. 配合自定义线程池​示

GO语言中函数命名返回值的使用

《GO语言中函数命名返回值的使用》在Go语言中,函数可以为其返回值指定名称,这被称为命名返回值或命名返回参数,这种特性可以使代码更清晰,特别是在返回多个值时,感兴趣的可以了解一下... 目录基本语法函数命名返回特点代码示例命名特点基本语法func functionName(parameters) (nam

使用shardingsphere实现mysql数据库分片方式

《使用shardingsphere实现mysql数据库分片方式》本文介绍如何使用ShardingSphere-JDBC在SpringBoot中实现MySQL水平分库,涵盖分片策略、路由算法及零侵入配置... 目录一、ShardingSphere 简介1.1 对比1.2 核心概念1.3 Sharding-Sp

Java 正则表达式的使用实战案例

《Java正则表达式的使用实战案例》本文详细介绍了Java正则表达式的使用方法,涵盖语法细节、核心类方法、高级特性及实战案例,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 目录一、正则表达式语法详解1. 基础字符匹配2. 字符类([]定义)3. 量词(控制匹配次数)4. 边

Python Counter 函数使用案例

《PythonCounter函数使用案例》Counter是collections模块中的一个类,专门用于对可迭代对象中的元素进行计数,接下来通过本文给大家介绍PythonCounter函数使用案例... 目录一、Counter函数概述二、基本使用案例(一)列表元素计数(二)字符串字符计数(三)元组计数三、C

使用Spring Cache本地缓存示例代码

《使用SpringCache本地缓存示例代码》缓存是提高应用程序性能的重要手段,通过将频繁访问的数据存储在内存中,可以减少数据库访问次数,从而加速数据读取,:本文主要介绍使用SpringCac... 目录一、Spring Cache简介核心特点:二、基础配置1. 添加依赖2. 启用缓存3. 缓存配置方案方案