IdentityServer4簡單入門demo系列 (二)API資源端
阿新 • • 發佈:2019-06-19
續上篇
二、API資源端
1、新建專案 ApiReSource 用來存放需要被保護的API,如下圖
2、引用nuget裡的 IdentityServer4.AccessTokenValidation類庫
3、新增一個Controller名叫 TestController
內容如下:
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace ApiReSource.Controllers { [Route("Test")] [Authorize] public class TestController : ControllerBase { [HttpGet] public IActionResult Get() { //這裡輸出測試資料 return new JsonResult(new { data = "ddd", password = "11223344" }); } } }
4、修改Startup.cs的內容至如下:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace ApiReSource { 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() //將認證服務新增到DI,配置"Bearer"作為預設方案 .AddAuthorization() .AddJsonFormatters(); services.AddAuthentication("Bearer") //將IdentityServer訪問令牌驗證處理程式新增到DI中以供身份驗證服務使用 .AddIdentityServerAuthentication(options => { //用於授權的地址 options.Authority = "http://localhost:5000/"; options.RequireHttpsMetadata = false; //該Api專案對應的IdentityServer的Api資源,與GetApiResources方法裡面的Api名稱對應 options.ApiName = "api1"; }); } // 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(); } } }
5、修改埠號為5001,如下圖
&n