透過 ASP.NET Core 寫一個簡易的 AD 帳號密碼驗證 Web API

  最近試著透過 ASP.NET Core 寫一個 AD 帳密修改的程式架構上大致是先有個 AD 驗證及些密碼修改的 Web API最後再寫一個桌面應用程式讓使用者自行修改這次完成的是帳密驗證的 Web 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輸入帳號密碼測試即可

发表评论

请注意:: 评论审核已启用,可能会耽误您的评论. 有没有必要重新提交您的评论.