最近試著透過 ASP.NET Core 寫一個 AD 帳密修改的程式,架構上大致是先有個 AD 驗證及些密碼修改的 Web API,最後再寫一個桌面應用程式,讓使用者自行修改。這次完成的是帳密驗證的 Web API,程式如下:
《專案範本》
- ASP .NET Core Web API
《NuGet 安裝套件》
- System.DirectoryServices.Protocols (AD 套件)
- Swashbuckle.AspNetCore (API 測試套件,或是在新增專案時,勾選 OpenAPI 亦可)
Services/UserPasswordService.cs
using System.DirectoryServices.Protocols;
using System.Net;
namespace AD.Services
{
public class UserPasswordService(IOptions<LdapSettings> ldapSettings)
{
private readonly string _ldapServer = ldapSettings.Value.Server;
private readonly string _domain = ldapSettings.Value.Domain;
public bool Validate(string username, string password)
{
try
{
var credentials = username;
using var connection = new LdapConnection(new LdapDirectoryIdentifier(_ldapServer));
connection.Credential = new NetworkCredential(username, password, _domain);
connection.AuthType = AuthType.Negotiate; // 使用 Negotiate 會先嘗試 Kerberos,失敗再改試 NTLM。
connection.Bind(); // 嘗試綁定,成功表示驗證通過
return true;
}
catch (LdapException)
{
return false; // 驗證失敗
}
}
}
}
Controllers/PasswordValidationController.cs
using AD.Services;
using AD.Models;
using Microsoft.AspNetCore.Mvc;
namespace AD.Controllers
{
[Route("Password-Validate")]
[ApiController]
public class PasswordValidationController(UserPasswordService userPassword) : ControllerBase
{
[HttpPost("validate")]
public IActionResult Validate([FromBody] LoginRequest request)
{
if (string.IsNullOrWhiteSpace(request.Username) || string.IsNullOrWhiteSpace(request.Password))
{
return BadRequest("使用者帳號或密碼不可為空白。");
}
var isValid = userPassword.ValidatePassword(request.Username, request.Password);
return isValid ? Ok("驗證成功。") : Unauthorized("驗證失敗。");
}
}
}
Models/LoginRequestDTO.cs
namespace AD.Models
{
public class LoginRequestDTO
{
public string Username { get; set; } // DTO (Data Transfer Object) 類型的屬性不需要初始化,因為它們的值由外部輸入資料 (例如 HTTP 請求) 決定。
public string Password { get; set; }
}
}
Models/LdapSettings.cs
namespace AD.Models
{
public class LdapSettings
{
public string Server { get; set; } = string.Empty;
public string Domain { get; set; } = string.Empty;
}
}
appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"LdapSettings": {
"Server": "dc.abc.com.tw", // 如果是用 Kerberos 驗證,AD 的伺服器不可以使用 IP。
"Domain": "abc"
}
}
Program.cs
using AD.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.Configure<LdapSettings>(builder.Configuration.GetSection("LdapSettings")); // 讀取 appsettings.json 的 LdapSettings 資料。
builder.Services.AddScoped<UserPasswordService>();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
// 讓 Swagger 只在開發環境時使用。
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
要測試時,透過 Swagger,輸入帳號密碼測試即可。









兄弟,軟體功力越來越強囉!
因為最近認識了一個很給力的兄弟叫 AI 😀