在現代的微服務架構中,身份認證和授權是一個非常重要的環節。IdentityServer4 是一個基于 ASP.NET Core 的開源框架,專門用于實現身份認證和授權。本文將詳細介紹如何在單項目中整合 IdentityServer4 和 API,以實現身份認證和授權功能。
在開始之前,確保你已經安裝了以下工具:
首先,我們需要創建一個 ASP.NET Core 項目。打開命令行工具,執行以下命令:
dotnet new webapi -n IdentityServer4WithApi
cd IdentityServer4WithApi
這將創建一個名為 IdentityServer4WithApi
的 ASP.NET Core Web API 項目。
接下來,我們需要將 IdentityServer4 添加到項目中。在命令行中執行以下命令:
dotnet add package IdentityServer4
這將安裝 IdentityServer4 的核心庫。
在 Startup.cs
文件中,我們需要配置 IdentityServer4。首先,添加以下命名空間:
using IdentityServer4;
using IdentityServer4.Test;
然后,在 ConfigureServices
方法中配置 IdentityServer4:
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentityServer()
.AddInMemoryClients(new List<Client>
{
new Client
{
ClientId = "client",
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = { "api1" }
}
})
.AddInMemoryApiScopes(new List<ApiScope>
{
new ApiScope("api1", "My API")
})
.AddTestUsers(new List<TestUser>
{
new TestUser
{
SubjectId = "1",
Username = "test",
Password = "password"
}
});
services.AddControllers();
}
在這個配置中,我們定義了一個客戶端 client
,它可以使用客戶端憑證授權類型來訪問 api1
資源。我們還定義了一個測試用戶 test
,密碼為 password
。
在 Configure
方法中,我們需要配置 API 資源。添加以下代碼:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseIdentityServer();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
接下來,我們創建一個受保護的 API。在 Controllers
文件夾中創建一個新的控制器 ProtectedController.cs
:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace IdentityServer4WithApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class ProtectedController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return Ok(new { message = "This is a protected API endpoint." });
}
}
}
在這個控制器中,我們使用了 [Authorize]
屬性來保護 Get
方法,只有經過身份認證的用戶才能訪問。
現在,我們可以測試我們的 API 了。首先,啟動項目:
dotnet run
然后,使用 Postman 或其他 API 測試工具來測試 API。
首先,我們需要獲取訪問令牌。發送以下 POST 請求:
POST /connect/token HTTP/1.1
Host: localhost:5001
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials&client_id=client&client_secret=secret&scope=api1
如果一切正常,你將收到一個包含訪問令牌的響應:
{
"access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6Ij...",
"expires_in": 3600,
"token_type": "Bearer"
}
接下來,使用獲取到的訪問令牌來訪問受保護的 API。發送以下 GET 請求:
GET /api/protected HTTP/1.1
Host: localhost:5001
Authorization: Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6Ij...
如果令牌有效,你將收到以下響應:
{
"message": "This is a protected API endpoint."
}
通過以上步驟,我們成功地在單項目中整合了 IdentityServer4 和 API,并實現了身份認證和授權功能。IdentityServer4 提供了強大的功能,可以輕松地集成到現有的 ASP.NET Core 項目中,幫助我們構建安全的微服務架構。
在實際項目中,你可能需要根據具體需求進一步配置 IdentityServer4,例如使用數據庫存儲用戶和客戶端信息、支持多種授權類型等。希望本文能為你提供一個良好的起點,幫助你更好地理解和應用 IdentityServer4。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。