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 安裝套件》

  • 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。

4 Responses

  1. Lao Sen Chang Tan IT Help » A desktop application for AD password modification written in .NET MAUI Blazor (Paired with Web API) Says |

    […]   完成了《AD 密碼驗證》與《AD 密碼修改》兩個 API 後,Next, use .NET MAUI Blazor to write desktop programs。After learning a little about Blazor,I feel so magical,It feels like putting a web page into an application,When running, you can also see Edge-related components running behind it in the "Job Manager",Then press F12 and there will be a developer tools window! But this also gave me some security concerns.。But the overall feeling is quite special.,I happen to be familiar with web page syntax,Use Razor to design UI screens,Feeling more friendly。 […]

  2. Lao Sen Chang Tan IT Help » Use ASP.NET Core to write a Web API that allows users to modify their AD passwords Says |

    […] API to verify AD password […]

  3. Sean Says |

    brother,The software skills are getting stronger and stronger!

    因為最近認識了一個很給力的兄弟叫 AI 😀

    Anson Reply |

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.