Недавно я попытался написать программу изменения пароля учетной записи AD через ASP.NET Core.,С точки зрения архитектуры обычно существует веб-API для аутентификации AD и изменения пароля.,Наконец, напишите настольное приложение,Позвольте пользователям изменять его самостоятельно。На этот раз завершено создание веб-API для проверки учетной записи и пароля.,Программа следующая:
NuGet 安裝套件
- System.DirectoryServices.Protocols (AD 套件)
- Swashbuckle.AspNetCore (API 測試套件,或是在新增專案時,勾選 OpenAPI 亦可)
Controllers/PasswordValidationController.cs
using AD.Services; using AD.Models; using Microsoft.AspNetCore.Mvc; namespace AD.Controllers { [Route("Password-Validate")] [ApiController] public class PasswordValidationController : ControllerBase { private readonly UserPasswordService _userPassword; public PasswordValidationController(UserPasswordService userPassword) { _userPassword = userPassword; } [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("驗證失敗。"); } } }
Services/UserPasswordService.cs
using System.DirectoryServices.Protocols; using System.Net; namespace AD.Services { public class UserPasswordService { private readonly string _ldapServer; private readonly string _domain; public UserPasswordService(IOptions<LdapSettings> ldapSettings) { _ldapServer = ldapSettings.Value.Server; _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; // 驗證失敗 } } } }
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,輸入帳號密碼測試即可。