二、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

相关文章

C++ Sort函数使用场景分析

《C++Sort函数使用场景分析》sort函数是algorithm库下的一个函数,sort函数是不稳定的,即大小相同的元素在排序后相对顺序可能发生改变,如果某些场景需要保持相同元素间的相对顺序,可使... 目录C++ Sort函数详解一、sort函数调用的两种方式二、sort函数使用场景三、sort函数排序

Java String字符串的常用使用方法

《JavaString字符串的常用使用方法》String是JDK提供的一个类,是引用类型,并不是基本的数据类型,String用于字符串操作,在之前学习c语言的时候,对于一些字符串,会初始化字符数组表... 目录一、什么是String二、如何定义一个String1. 用双引号定义2. 通过构造函数定义三、St

Pydantic中Optional 和Union类型的使用

《Pydantic中Optional和Union类型的使用》本文主要介绍了Pydantic中Optional和Union类型的使用,这两者在处理可选字段和多类型字段时尤为重要,文中通过示例代码介绍的... 目录简介Optional 类型Union 类型Optional 和 Union 的组合总结简介Pyd

Vue3使用router,params传参为空问题

《Vue3使用router,params传参为空问题》:本文主要介绍Vue3使用router,params传参为空问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录vue3使用China编程router,params传参为空1.使用query方式传参2.使用 Histo

使用Python自建轻量级的HTTP调试工具

《使用Python自建轻量级的HTTP调试工具》这篇文章主要为大家详细介绍了如何使用Python自建一个轻量级的HTTP调试工具,文中的示例代码讲解详细,感兴趣的小伙伴可以参考一下... 目录一、为什么需要自建工具二、核心功能设计三、技术选型四、分步实现五、进阶优化技巧六、使用示例七、性能对比八、扩展方向建

使用Python实现一键隐藏屏幕并锁定输入

《使用Python实现一键隐藏屏幕并锁定输入》本文主要介绍了使用Python编写一个一键隐藏屏幕并锁定输入的黑科技程序,能够在指定热键触发后立即遮挡屏幕,并禁止一切键盘鼠标输入,这样就再也不用担心自己... 目录1. 概述2. 功能亮点3.代码实现4.使用方法5. 展示效果6. 代码优化与拓展7. 总结1.

使用Python开发一个简单的本地图片服务器

《使用Python开发一个简单的本地图片服务器》本文介绍了如何结合wxPython构建的图形用户界面GUI和Python内建的Web服务器功能,在本地网络中搭建一个私人的,即开即用的网页相册,文中的示... 目录项目目标核心技术栈代码深度解析完整代码工作流程主要功能与优势潜在改进与思考运行结果总结你是否曾经

Linux中的计划任务(crontab)使用方式

《Linux中的计划任务(crontab)使用方式》:本文主要介绍Linux中的计划任务(crontab)使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、前言1、linux的起源与发展2、什么是计划任务(crontab)二、crontab基础1、cro

kotlin中const 和val的区别及使用场景分析

《kotlin中const和val的区别及使用场景分析》在Kotlin中,const和val都是用来声明常量的,但它们的使用场景和功能有所不同,下面给大家介绍kotlin中const和val的区别,... 目录kotlin中const 和val的区别1. val:2. const:二 代码示例1 Java

C++变换迭代器使用方法小结

《C++变换迭代器使用方法小结》本文主要介绍了C++变换迭代器使用方法小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录1、源码2、代码解析代码解析:transform_iterator1. transform_iterat