私は開発中です5 のウェブアプリケーションを使用するEntity Framework 5 データベースファーストアプローチ。私はオウィンユーザーの認証用です。以下は、アカウント コントローラー内のログイン方法を示しています。
public ActionResult Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var user = _AccountService.VerifyPassword(model.UserName, model.Password, false);
if (user != null)
{
var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, model.UserName), }, DefaultAuthenticationTypes.ApplicationCookie, ClaimTypes.Name, ClaimTypes.Role);
identity.AddClaim(new Claim(ClaimTypes.Role, "guest"));
identity.AddClaim(new Claim(ClaimTypes.GivenName, "A Person"));
identity.AddClaim(new Claim(ClaimTypes.Sid, user.userID)); //OK to store userID here?
AuthenticationManager.SignIn(new AuthenticationProperties
{
IsPersistent = model.RememberMe
}, identity);
return RedirectToAction("Index", "MyDashboard");
}
else
{
ModelState.AddModelError("", "Invalid username or password.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
ご覧の通り、私はクレームアイデンティティそれにいくつかのクレームを追加し、それをオウィン使用して認証マネージャーサインインを実行します。
私が抱えている問題は、コントローラーでも Razor ビューでも、アプリケーションの残りの部分でクレームにアクセスする方法がわからないことです。
私はこのチュートリアルに記載されているアプローチを試しました
たとえば、コントローラコードでこれを試して、クレームに渡された値にアクセスしようとしましたが、user.Claimsはnullに等しくなります。
var ctx = HttpContext.GetOwinContext();
ClaimsPrincipal user = ctx.Authentication.User;
IEnumerable<Claim> claims = user.Claims;
おそらく私はここで何かを見逃しているのでしょう。
アップデート
Darin の回答に基づいて、彼のコードを追加しましたが、それでも Claims へのアクセスが表示されません。identity.Claims にマウスを移動したときに表示される以下のスクリーンショットを参照してください。
ベストアンサー1
これを試して:
[Authorize]
public ActionResult SomeAction()
{
var identity = (ClaimsIdentity)User.Identity;
IEnumerable<Claim> claims = identity.Claims;
...
}