微軟提供了一些針對IdentityServer4的項目模板,在命令行中輸入” dotnet new -i IdentityServer4.Templates“即可安裝,安裝好后可以看到當前已安裝的項目模板,其中有一個"is4empty",其實就是一個asp.net core 應用裝了IdentityServer4包。在命令行中輸入:dotnet new is4empty -n Projectname 就會根據這個模板生成一個新項目。下圖是我的項目,一個api客戶端(idsapi或者jwtdemo)、一個mvc客戶端(那個client),一個identityserver4服務端(idstest),其中Api客戶端是受保護的Api資源,Mvc客戶端是第三方客戶端,用於訪問被保護的Api客戶端,可以看成是任意后端程序。
2:idstest:內部結構
直接貼代碼:
Config.cs
public static class Config { public static IEnumerable<IdentityResource> IdentityResources => new IdentityResource[] { new IdentityResources.OpenId(), new IdentityResources.Profile(), }; public static IEnumerable<ApiScope> ApiScopes => new ApiScope[] { new ApiScope("secretapi"), //new ApiScope("scope2"), }; public static IEnumerable<ApiResource> ApiResources => new ApiResource[] { new ApiResource("secretapi","Secret Api") { //!!!重要 請注意 在ApiSource里面一定要添加這個,不然永遠是401 Scopes = { "secretapi" } }, //new ApiResource("api2","#api2") //{ // //!!!重要 // Scopes = { "scope2"} //}, }; public static IEnumerable<Client> Clients => new Client[] { new Client { ClientId = "apiClientCd", ClientName = "Client Credentials Client", AllowedGrantTypes = GrantTypes.ClientCredentials, ClientSecrets = { new Secret("apiSecret".Sha256()) }, AllowedScopes = { "secretapi" } }, }; }
StartUp.cs
public void ConfigureServices(IServiceCollection services) { // uncomment, if you want to add an MVC-based UI //services.AddControllersWithViews(); var builder = services.AddIdentityServer(options => { // see https://identityserver4.readthedocs.io/en/latest/topics/resources.html options.EmitStaticAudienceClaim = true; }); //.AddInMemoryIdentityResources(Config.IdentityResources) //.AddInMemoryApiScopes(Config.ApiScopes) //.AddInMemoryApiResources(Config.GetApis()) //.AddInMemoryClients(Config.GetClients()); // in-memory, code config builder.AddInMemoryIdentityResources(Config.IdentityResources); builder.AddInMemoryApiScopes(Config.ApiScopes); //添加API資源 builder.AddInMemoryApiResources(Config.ApiResources); builder.AddInMemoryClients(Config.Clients); // not recommended for production - you need to store your key material somewhere secure builder.AddDeveloperSigningCredential(); }
然后在添加中間件:app.UseIdentityServer();
2:idsapi
這個就是受保護的api資源。
首先定義一個api
我是直接使用的自帶的api,然后加了一個特性:Authorize
這個時候用postman訪問就會出現401
這個時候啟動idtest,拿到token,這里使用的是客戶端模式。
如圖
里面的值與配置相同。
在這里拿到token 之后還需要在API項目里面添加如下代碼
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0); services.AddAuthentication("Bearer").AddIdentityServerAuthentication(r => { //認證地址 r.Authority = "http://localhost:6666"; //權限標識 r.ApiName = "secretapi"; //是否必需HTTPS r.RequireHttpsMetadata = false; });
添加中間件:
app.UseAuthentication();
app.UseAuthorization();
將token復制過去再訪問就可成功:
踩坑:在ApiSource里面一定要添加Scope,不然會不成功
原文參考:https://www.cnblogs.com/liujiabing/p/11460486.html