ASP.NET MVC 使用 Windows 驗證 Windows Authentication


  1. Identity
    1. User.Identity
    2. Windows Identity
    3. Authorize Filter
  2. IIS
    1. IIS Express

筆記開發 ASP.NET MVC Intranet 環境專案時,如何使用 Windows 驗證。

logo

Identity

User.Identity

可以取得包含 Name, IsAnonymous, IsAuthenticated, Groups 等 Property。

Windows Identity

User.Identity 以及 WindowsIdentity 同樣 Implements IIdentity,因此可以 User.Identity 轉型為 WindowsIdentity。轉型後可以迭代 WindowsIdentity Object 的 Groups Property,並對照為 NTAccount,則可以取得 User 所屬的所有 AD 群組名稱。

using System.Security.Principal;
var user = (WindowsIdentity)User.Identity;
foreach (var group in user.Groups)
{
    group.Translate(typeof(NTAccount)).ToString();
}

Authorize Filter

在啟用 Windows 驗證的情形中,使用 Authorize Filter 可以來限制存權身分的 Users 與 Roles。

其中 Users 就是 User.Identity.Name,而 Roles 則是 Identity 所屬於 AD群組名稱。

[Authorize(Roles = "AdGroupName", Users ="AdUserName")]
public ActionResult Action()
{
  ...
}

IIS

IIS Express

在專案開發中,可以對專案名稱按 ,從屬性設定中啟用 Windows 驗證。