C#
定石5: User.Identity.Nameでユーザー情報取得
出典: 業務イントラの認証 — Windows認証 / Forms認証 / Cookie の使い分けで業務SE が踏む選択 — 定石5: User.Identity.Nameでユーザー情報取得
// ✅定石5: User.Identityからの情報取得
public class HomeController : Controller
{
[Authorize]
public ActionResult Profile()
{
//認証済みか
bool isAuth = User.Identity.IsAuthenticated;
//ユーザー名(認証方式で形式が違う)
string userName = User.Identity.Name;
// Windows認証: "MYDOMAIN\\suzuki"
// Forms認証: "suzuki"(SetAuthCookieで渡した値)
// Cookie認証: "suzuki@example.com"(IdentityのUserName)
// Role判定
bool isAdmin = User.IsInRole("Admin");
bool isInAdGroup = User.IsInRole("MYDOMAIN\\SalesGroup");
// ClaimsIdentityから追加情報(Cookie認証時)
if (User.Identity is System.Security.Claims.ClaimsIdentity claims)
{
string email = claims.FindFirst(System.Security.Claims.ClaimTypes.Email)?.Value;
}
return View();
}
}
▸ この snippet は実行結果未収録
▸ 実行結果は未収録です
Source収録記事
この snippet は記事の「定石5: User.Identity.Nameでユーザー情報取得」セクションに登場する。コードの前後の文脈・ハマりどころの解説は記事本文で。
同じ記事から
4 件// ✅定石1: Action内でユーザー名取得 public class HomeController : Controller { public ActionResult Index()未収録
定石1: Windows認証—最小設定でイントラSSO
#e927f6952e5d
// ✅定石2: Login ActionでのCookie発行 using System.Web.Security; public class AccountController : Controller未収録
定石2: Forms認証—フォームログイン+ Cookie
#9451e4bcfa68
// ✅定石3: OWIN Startup.csでのCookie認証設定 using Owin; using Microsoft.Owin; using Microsoft.Owin.Security.Cookies;未収録
定石3: Cookie認証— OWIN + ASP.NET Identity
#646899dc7794
// ✅定石4: [Authorize] 属性で認可制御 public class OrderController : Controller { [Authorize] //ログイン必須(未ログインはLoginUrlにリダイレクト)未収録
定石4: [Authorize]属性で認可制御
#37d5f30b5333
