1.新建項目
新建ASP .Net Core項目IdentityServer.EasyDemo.IdentityServer,選擇.net core 2.0

1

2
引用IdentityServer4

3
2.定義Api資源
添加一個Config.cs文件,在其中定義Api資源
Api資源指上述的Api,可以有多個,在這里設置了,並且Api的配置與之匹配,IdentityServer才能識別那個Api
eg.IdentityServer項目的Api資源池里面有一個名叫"api1"的Api資源,Api項目中設置ApiName為"api1",則雙方匹配
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
//參數是資源名稱,資源顯示名稱
new ApiResource("api1", "My API")
};
}
3.定義客戶端Client
繼續在Config.cs中添加Client
Client指的是各個調用服務的客戶端,可以有多個
用戶要設置ClientId,這是它的唯一標志,在Client列表里面,ClientId不能重復,ClientSecrets是用來驗證用戶的密碼,AllowedScopes記錄了它的權限范圍
注意:可以多個客戶端共用一個ClientId,則對於IdentityServer來說,這些客戶端都是一個"Client"。這個在你的客戶端都具有相同的權限范圍,或者說要求完全一樣的時候,可以簡化為這樣。
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
ClientId = "client",
AllowedGrantTypes = GrantTypes.ClientCredentials,
// 用於驗證的secret
ClientSecrets =
{
new Secret("secret".Sha256())
},
// 允許的范圍
AllowedScopes = { "api1" }
}
};
}
4.配置IdentityServer
在services里面添加IdentityServer,並且將Api資源和Client集合放入內存,交給IdentityServer
public void ConfigureServices(IServiceCollection services)
{
//配置IdentityServer,包括把Api資源,Client集合,密鑰保存在內存
services.AddIdentityServer()
//設置臨時簽名憑據
.AddDeveloperSigningCredential()
//從Config類里面讀取剛剛定義的Api資源
.AddInMemoryApiResources(Config.GetApiResources())
//從Config類里面讀取剛剛定義的Client集合
.AddInMemoryClients(Config.GetClients());
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseIdentityServer();
}
5.在屬性中將IdentityServer項目的端口號設置為5000

1
6.查看IdentityServer的相關信息
通過這個網址查看:http://localhost:5000/.well-known/openid-configuration

2
{
"issuer": "http://localhost:5000", "jwks_uri": "http://localhost:5000/.well-known/openid-configuration/jwks", "authorization_endpoint": "http://localhost:5000/connect/authorize", "token_endpoint": "http://localhost:5000/connect/token", "userinfo_endpoint": "http://localhost:5000/connect/userinfo", "end_session_endpoint": "http://localhost:5000/connect/endsession", "check_session_iframe": "http://localhost:5000/connect/checksession", "revocation_endpoint": "http://localhost:5000/connect/revocation", "introspection_endpoint": "http://localhost:5000/connect/introspect", "frontchannel_logout_supported": true, "frontchannel_logout_session_supported": true, "backchannel_logout_supported": true, "backchannel_logout_session_supported": true, "scopes_supported": [ "api1", "offline_access" ], "claims_supported": [], "grant_types_supported": [ "authorization_code", "client_credentials", "refresh_token", "implicit" ], "response_types_supported": [ "code", "token", "id_token", "id_token token", "code id_token", "code token", "code id_token token" ], "response_modes_supported": [ "form_post", "query", "fragment" ], "token_endpoint_auth_methods_supported": [ "client_secret_basic", "client_secret_post" ], "subject_types_supported": [ "public" ], "id_token_signing_alg_values_supported": [ "RS256" ], "code_challenge_methods_supported": [ "plain", "S256" ] }