IdentityServer4 系列 【三】-- 资源Api端开发

1、新建.net core 3.1 Web 空项目。

2、Nuget 增加 IdentityServer4.AccessTokenValidation (3.0.1)、Autofac(6.0.0)目前使用的版本

3、添加HomeController(首先要新建Controllers文件夹,并控制器新建在此文件夹内)

 1 using Microsoft.AspNetCore.Mvc;
 2 using Microsoft.AspNetCore.Authorization;
 3 namespace UserApi.Controllers
 4 {
 5     [Authorize] //鉴权
 6     [ApiController]
 7     [Route("api/{controller}")]
 8     public class HomeController : ControllerBase
 9     {
10         [Route("index")]
11         public IActionResult Index()
12         {
13             return Content("12122");
14         }
15     }
16 }

4、修改Startup文件

修改 ConfigureServices 方法

 1 services.AddControllersWithViews();
 2 
 3             services.AddAuthentication("Bearer").AddIdentityServerAuthentication(r =>
 4             {
 5                 r.Authority = "http://localhost:5000"; //鉴权端的地址
 6                 r.ApiName = "userapi"; //资源名
 7                 r.RequireHttpsMetadata = false; //不用https
 8             });
 9 
10 //跨域
11             services.AddCors(options =>
12             {
13                 options.AddPolicy("any", builder =>
14                 {
15                     builder.WithOrigins("*").AllowAnyHeader();//添加头跨域
16                 });
17             });

修改 Configure 方法

 1 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
 2         {
 3             if (env.IsDevelopment())
 4             {
 5                 app.UseDeveloperExceptionPage();
 6             }
 7 
 8             app.UseAuthentication();  //鉴权
 9 
10             app.UseRouting();
11 
12             app.UseCors("any");
13 
14             app.UseAuthorization(); //授权
15 
16             app.UseEndpoints(endpoints =>
17             {
18                 endpoints.MapDefaultControllerRoute();
19             });
20         }

5、打完收功,启动之。

6、使用 PostMan 通过Token使用资源

7、资源端好了,也可以用postman获取成功了,下一步就是如果在客户端调用。

原文地址:https://www.cnblogs.com/youyuan1980/p/14097315.html