Write a simple AD account and password verification Web API through ASP.NET Core

Recently I tried to write an AD account password modification program through ASP.NET Core.,In terms of architecture, there is generally a Web API for AD authentication and password modification.,Finally, write a desktop application,Let users modify it themselves。What is completed this time is the Web API for account and password verification.,The program is as follows:

"Project Template"

  • ASP .NET Core Web API

NuGet Installation Kit

  • System.DirectoryServices.Protocols (AD suite)
  • Swashbuckle.AspNetCore (API test suite,Or when adding a new project,You can also check 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();

When to test,Via Swagger,Enter your account and password to test。

5 則留言

  1. Sean says:

    brother,The software skills are getting stronger and stronger!

    1. Anson says:

      Because I recently met a very powerful brother named AI 😀

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.