前言
網上關於Identity Server4的資料有挺多的,之前是一直看楊旭老師的,最近項目中有使用到,在使用.NET Core3.1的時候有一些不同。所以在此記錄一下。
預備知識: https://www.cnblogs.com/cgzl/p/9405796.html
本文內容參考
如楊旭老師所說,官方文檔真的很詳細,有時間建議大家看下官方文檔。
建立Authorization Server
建立ASP.Net Core項目使用空模板。
項目建立之后,運行方式改為使用控制台運行而不是IIS Express,以便查看各種debug信息。
這個已成為習慣,也是學習楊老師的,確實比較方便,當然如果不喜歡可以不設置,只需要端口號配置的時候對應好就可以的。

修改后文件代碼為:
{
"profiles": {
"IdentityServer4.AuthServer": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
端口號為5000,此時運行程序,會顯示出Hello World!,默認的,沒有修改。

安裝Identity Server4

點擊安裝就好啦。
配置Identity Server4
API和客戶端
API的配置和之前有所不同,之前是
ApiResources,現在分為ApiResources和ApiScopes,后續會說到。
using IdentityServer4.Models;
using IdentityServer4.Test;
using System.Collections.Generic;
namespace IdentityServer4.AuthServer.Configuration
{
public class InMemoryConfiguration
{
/// <summary>
/// Api Scopes
/// </summary>
/// <returns></returns>
public static IEnumerable<ApiScope> ApiScopes()
{
return new List<ApiScope>
{
new ApiScope("scope1","scope1")
};
}
/// <summary>
/// ApiResources
/// </summary>
/// <returns></returns>
public static IEnumerable<ApiResource> ApiResources()
{
return new[]
{
new ApiResource
{
Name = "api1",
DisplayName = "My Api1",
Scopes = { "scope1" }
}
};
}
/// <summary>
/// Clients
/// </summary>
/// <returns></returns>
public static IEnumerable<Client> Clients()
{
return new[]
{
new Client
{
ClientId = "client",
AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = { "scope1" }
}
};
}
/// <summary>
/// Users
/// </summary>
/// <returns></returns>
public static IEnumerable<TestUser> Users()
{
return new[]
{
new TestUser
{
SubjectId = "1",
Username = "mail@qq.com",
Password = "password"
}
};
}
}
}
ApiScopes: 這個應該怎么翻譯我也不清楚,API范圍?如果沒理解錯的話,就是給之前的ApiResources進行了一個分組。授權的時候會驗證Scope。
ApiResources:比如官網的第一個demo,可能會有疑問,你怎么知道我是api1呢?其實,就沒有驗證,只要有授權碼就可以訪問的。如果說,我只要api1的話,那就用到ApiResources了,生產環境中,也必然是需要用到的。
加載資源和客戶端
修改Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddTestUsers(InMemoryConfiguration.Users().ToList())
.AddInMemoryClients(InMemoryConfiguration.Clients())
.AddInMemoryApiScopes(InMemoryConfiguration.ApiScopes())
.AddInMemoryApiResources(InMemoryConfiguration.ApiResources());
}
當然,也需要app.UseIdentityServer();
首次啟動時,Identity Server4將創建一個開發人員簽名密鑰,該文件名為
tempkey.rsa。不必將該文件簽入源代碼管理中,如果不存在該文件將被重新創建。也就是AddDeveloperSigningCredential()。 這個方法只適合用於Identity Server4在單個機器運行, 如果是生產環境你得使用AddSigningCredential()這個方法.
運行一下,發現並沒有什么改變,不過打開:http://localhost:5000/.well-known/openid-configuration,則應該看到所謂的發現文檔。發現文檔是身份服務器中的標准端點。客戶端和API將使用發現文檔來下載必要的配置數據。

獲取Token
打開Postman,按照配置的輸入然后試一下

獲取到Token,控制台輸出如下:

這里是有用戶的信息的,但是我們可以把用戶信息去掉,然后GrantType改為client_credentials,我們設置的是 ResourceOwnerPasswordAndClientCredentials 這個GrantType,所以使用用戶名密碼以及使用ClientCredentials都可以。

不過此時控制台會有區別,沒有用戶信息了。

美化美化UI
Identity Server 4 提供了一套QuickStart UI
https://github.com/IdentityServer/IdentityServer4.Quickstart.UI
此存儲庫包含UI所需的控制器,模型,視圖和CSS文件。只需下載/克隆並將其復制到Web項目中即可。
打開項目根目錄,運行Powershell,然后輸入命令:
iex ((New-Object System.Net.WebClient).DownloadString('https://raw.githubusercontent.com/IdentityServer/IdentityServer4.Quickstart.UI/main/getmain.ps1'))

不過可能你會遇到我前三次那種錯誤,嗯,訪問不了,那就全局或者先下載下來人工粘貼過去吧~
好了以后我們的項目是醬紫的:

由於有wwwroot下很多靜態文件, 所以asp.net core 需要啟用服務靜態文件的功能: 修改Startup的Configure方法
先看修改前的樣子吧
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseIdentityServer();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
});
}
修改后
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseIdentityServer();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}"
);
});
}
是不是拋異常了?

因為我們現在有UI了,所以不要忘記在ConfigureServices里面注冊MVC。
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddTestUsers(InMemoryConfiguration.Users().ToList())
.AddInMemoryClients(InMemoryConfiguration.Clients())
.AddInMemoryApiScopes(InMemoryConfiguration.ApiScopes())
.AddInMemoryApiResources(InMemoryConfiguration.ApiResources());
}
然后運行一下試試:

登錄一下~

好了,現在我們已經可以登錄成功了。
登錄界面可以自定義的~,OK,今天就到這里
計划
接下來會說一下
- 建立我們的API項目並使用Token測試接口
- 建立一個MVC客戶端項目訪問我們的API
- 建立一個JS(Vue)客戶端訪問我們的API項目
End
推廣下自己的公眾號一個逗逼的程序員,主要記錄自己工作中解決問題的思路分享及學習過程中的筆記。絕對不會程序員販賣程序員的焦慮來割韭菜。

