IdentityServer4簡單入門demo系列 (一)認證服務端
阿新 • • 發佈:2019-06-19
目錄
一、認證服務端
二、API資源端
三、呼叫客戶端
詳細步驟
一、認證服務端
1、新建一個名為“CertifiedCenter”的 asp.net core web應用程式,如下圖
2、新增IdentityServer4的2個引用 IdentityServer4 和 IdentityServer4.AccessTokenValidation,如下圖:
3、新增Config.cs類,如下圖:
Config.cs的內容如下:
using IdentityServer4.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CertifiedCenter { public class Config { public static IEnumerable<ApiResource> GetApiResources() { return new List<ApiResource> { //引數是資源名稱,資源顯示名稱 new ApiResource("GbaseDataSourceApi", "GbaseDataSourceApi") }; } public static IEnumerable<Client> GetClients() { return new List<Client> { new Client { ClientId = "clientId", AllowedGrantTypes = GrantTypes.ClientCredentials, // 用於驗證的secret ClientSecrets = { new Secret("123456".Sha256()) }, // 允許的範圍 AllowedScopes = { "api1" } } }; } } }
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.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace CertifiedCenter { 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.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddIdentityServer() //設定臨時簽名憑據 .AddDeveloperSigningCredential() //從Config類裡面讀取剛剛定義的Api資源 .AddInMemoryApiResources(Config.GetApiResources()) //從Config類裡面讀取剛剛定義的Client集合 .AddInMemoryClients(Config.GetClients()); } // 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.UseExceptionHandler("/Home/Error"); app.UseHsts(); }//app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); app.UseIdentityServer(); } } }
5、最後一步,修改埠號,把埠改為5000,如下圖
明天做 API資源端的