簡介
Identity Server 4(以下簡稱ID4)是一個基于oauth2和OpenID的身份認證組件,基于這個組件可以快速開發自己的身份認證網站,支持單點登錄,快速完成工業級的身份認證系統。ID4也是dotnetcore推薦的身份認證組件。
本教程將基于dotnetcore1.1.2來實現一個完整的ID4身份網站,并搭配各種應用來使用這個認證系統。
目前ID4對于dotnetcore2.0.0的支持還有問題,在問題修復后,會升級到.net core 2.0.0
和core一樣,ID4也完全支持linux和Mac,大家可以按照下面的步驟,在linux上運行。當然windows上有一個ubuntu的子系統,可以用來驗證,就不需要單獨去安裝linux虛擬機了。關于windows上的ubuntu子系統,可以參看這個教程
環境準備
首先我們需要配置好環境,這里我們使用chocolatey來快速把環境準備好。 關于chocolatey的使用請參看chocolate使用教程。從上到下,我們安裝了:
- curl用于下載文件.
- git用于管理代碼,在本教程中主要是比較修改的文件。
- visualstudiocode主要是用于編輯代碼。
- dotnetcore-sdk安裝了兩個,主要是ID4目前還不支持.net core 2.0.
choco install cUrl -y
choco install git -y
choco install visualstudiocode -y
choco install dotnetcore-sdk --version 1.1.2 -y
choco install dotnetcore-sdk --version 2.0.0 -y
準備asp.net core MVC基礎代碼
- 使用管理員權限打開一個CMD窗口
- 創建目錄并進入這個目錄
mkdir ID4.Learn && cd ID4.Learn
- 在根目錄下創建global.json文件以便切換dotnet 2.0.0 到1.0.4版本
{ "sdk": { "version": "1.0.4" } }
也可以使用下面的命令從github直接下載這個文件
curl -k -O https://raw.githubusercontent.com/miemengniao/ID4.Learn/step-1/global.json
- 運行dotnet CLI命令創建一個帶Identity的MVC框架程序ID4.Server
dotnet new mvc -au Individual -o ID4.Server
dotnet CLI的命令參數,可以通過dotnet -h來查看
此處的-au Individual
表示生成的MVC文件帶有認證信息,-o ID4.Server
表示輸出到ID4.Server目錄,項目名稱也是ID4.Server. - 轉到ID4.Server目錄下,運行下面命令來查看生成的MVC程序
cd ID4.Server dotnet restore dotnet build dotnet run
在dotnet 2.0以后,運行
dotnet run
的時候會自動運行dotnet restore
和dotnet build
。
運行結果如下:
好了,web服務已經啟動監聽5000端口,我們打開瀏覽器訪問 http://localhost:5000。結果如下圖: asp.net core的網站已經成功跑起來了??!
添加ID4的支持
1. 添加ID4的組件
首先我們需要添加ID4的assembly, 在ID4.Server目錄下運行dotnet add package IdentityServer4.AspNetIdentity
。因為IdentityServer4.AspNetIdentity
會引用IdentityServer4
,所以我們不需要單獨在添加它了。
2. 增加oauth2的配置信息
我們現在來為mvc程序添加ID4所需要的配置信息。主要是添加三個靜態方法GetIdentityResources
來返回支持的Claim種類。GetApiResources
來返回支持的webapi資源,GetClients
來返回支持的客戶端信息。包括客戶ID,密碼等信息。
public class Config
{
// scopes define the resources in your system
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
};
}
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource("api1", "My API")
};
}
// clients want to access resources (aka scopes)
public static IEnumerable<Client> GetClients()
{
// client credentials client
return new List<Client>
{
new Client
{
ClientId = "mvc",
ClientName = "MVC Client",
AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
RequireConsent = false,
ClientSecrets =
{
new Secret("secret".Sha256())
},
RedirectUris = { "http://localhost:5002/signin-oidc" },
PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" },
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"api1"
},
AllowOfflineAccess = true
}
};
}
}
運行下面的命令,可以直接從github下載上述config.cs
curl -k -O https://raw.githubusercontent.com/miemengniao/ID4.Learn/step-1/ID4.Server/Config.cs
3. 注冊ID4的服務
準備好了ID4的配置文件后,現在需要來注入ID4的服務了。在startup.cs
文件的ConfigureServices
方法中注入IdentityService。
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
// Adds IdentityServer
services.AddIdentityServer()
.AddTemporarySigningCredential()
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients())
.AddAspNetIdentity<ApplicationUser>();
}
4. 使用ID4的服務
在注入了ID4的服務后,我們需要使用ID4的服務了。在startup.cs
文件的Configure
方法中使用Identity。
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseIdentity();
// Adds IdentityServer
app.UseIdentityServer();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
修改完成的Startup.cs文件,可以通過下面的命令直接下載
curl -k -O https://raw.githubusercontent.com/miemengniao/ID4.Learn/step-1/ID4.Server/Startup.cs
5. 重新編譯運行
好了,所有的工作都做完了,我們可以運行新的網站了,使用下面的命令重新運行網站。
dotnet restore
dotnet build
dotnet run
檢查確認ID4服務器已經配置好了。
在瀏覽器中訪問http://localhost:5000/.well-known/openid-configuration
地址,查看ID4的配置信息,如果返回結果類似于下圖,那么恭喜,ID4的認證服務器已經成功建立!!??
下一節,我們會配置一個MVC客戶端來使用這個ID4認證服務器