MVC 5 액세스 클레임 ID 사용자 데이터
엔티티 프레임워크 5 데이터베이스 퍼스트 접근 방식을 사용하여 MVC 5 웹 애플리케이션을 개발하고 있습니다.저는 사용자 인증을 위해 OWIN을 사용하고 있습니다.아래는 내 계정 컨트롤러 내의 로그인 방법을 보여줍니다.
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);
}
보시다시피, 클레임 ID를 생성하고 클레임 ID에 여러 클레임을 추가한 다음 Authentication Manager를 사용하여 로그인을 수행하는 OWIN에 전달합니다.
문제는 컨트롤러 또는 레이저 보기에서 나머지 응용 프로그램의 클레임에 액세스하는 방법을 잘 모른다는 것입니다.
이 튜토리얼에 나열된 접근 방식을 시도했습니다.
예를 들어, 사용자가 클레임에 전달된 값에 액세스하기 위해 컨트롤러 코드에서 이 작업을 시도했습니다.클레임은 null과 같습니다.
var ctx = HttpContext.GetOwinContext();
ClaimsPrincipal user = ctx.Authentication.User;
IEnumerable<Claim> claims = user.Claims;
아마도 제가 여기서 뭔가를 놓치고 있는 것 같습니다.
갱신하다
다린의 답변에 따라 코드를 추가했지만 클레임에 대한 액세스 권한이 보이지 않습니다.아래 스크린샷에서 신원을 가리킬 때 보이는 것을 확인하십시오.주장하다.

사용해 보십시오.
[Authorize]
public ActionResult SomeAction()
{
var identity = (ClaimsIdentity)User.Identity;
IEnumerable<Claim> claims = identity.Claims;
...
}
다음과 같은 작업도 수행할 수 있습니다.
//Get the current claims principal
var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
var claims = identity.Claims;
갱신하다
코멘트에 따라 추가 설명을 제공합니다.
시스템 내에서 다음과 같이 사용자를 작성하는 경우:
UserManager<applicationuser> userManager = new UserManager<applicationuser>(new UserStore<applicationuser>(new SecurityContext()));
ClaimsIdentity identity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
귀하는 귀하의 신원과 관련된 일부 클레임을 자동으로 작성해야 합니다.
사용자 인증 후 사용자 지정 클레임을 추가하려면 다음과 같이 수행합니다.
var user = userManager.Find(userName, password);
identity.AddClaim(new Claim(ClaimTypes.Email, user.Email));
그 주장들은 다린이 위에서 대답한 것처럼 또는 내가 대답한 것처럼 다시 읽을 수 있습니다.
아래로 전화를 걸어 ID를 전달하면 클레임이 지속됩니다.
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = persistCookie }, identity);
필요한 것을 확인하기 위해 자체 확장 클래스를 만들기 때문에 컨트롤러나 보기에 필요할 때는 다음과 같은 사용법만 네임스페이스에 추가합니다.
public static class UserExtended
{
public static string GetFullName(this IPrincipal user)
{
var claim = ((ClaimsIdentity)user.Identity).FindFirst(ClaimTypes.Name);
return claim == null ? null : claim.Value;
}
public static string GetAddress(this IPrincipal user)
{
var claim = ((ClaimsIdentity)user.Identity).FindFirst(ClaimTypes.StreetAddress);
return claim == null ? null : claim.Value;
}
public ....
{
.....
}
}
내 컨트롤러에서:
using XXX.CodeHelpers.Extended;
var claimAddress = User.GetAddress();
내 면도기 안에서:
@using DinexWebSeller.CodeHelpers.Extended;
@User.GetFullName()
항상 클레임을 사용하지 않으려는 경우 이 방법을 사용할 수 있습니다.벤 포스터의 이 튜토리얼을 보세요.
public class AppUser : ClaimsPrincipal
{
public AppUser(ClaimsPrincipal principal)
: base(principal)
{
}
public string Name
{
get
{
return this.FindFirst(ClaimTypes.Name).Value;
}
}
}
그런 다음 기본 컨트롤러를 추가할 수 있습니다.
public abstract class AppController : Controller
{
public AppUser CurrentUser
{
get
{
return new AppUser(this.User as ClaimsPrincipal);
}
}
}
컨트롤러에서 다음 작업을 수행할 수 있습니다.
public class HomeController : AppController
{
public ActionResult Index()
{
ViewBag.Name = CurrentUser.Name;
return View();
}
}
Darin의 답변에 대해 자세히 알아보려면 FindFirst 방법을 사용하여 구체적인 주장을 확인할 수 있습니다.
var identity = (ClaimsIdentity)User.Identity;
var role = identity.FindFirst(ClaimTypes.Role).Value;
이것도 할 수 있습니다.
IEnumerable<Claim> claims = ClaimsPrincipal.Current.Claims;
@Rosdi Kasim의 대답은 짧고 단순화된 버전입니다.
string claimvalue = ((System.Security.Claims.ClaimsIdentity)User.Identity).
FindFirst("claimname").Value;
Claimname검색하려는 클레임입니다. 즉, "StreedAddress" 클레임을 찾고 있는 경우 위의 답변은 다음과 같습니다.
string claimvalue = ((System.Security.Claims.ClaimsIdentity)User.Identity).
FindFirst("StreedAddress").Value;
IEnumberable을 쿼리하려면 system.linq를 참조해야 합니다.
다음 작업에 필요한 확장 개체를 제공합니다.
CaimsList.FirstOrDefault(x=>x.Type =="variableName").toString();
Request.GetOwinContext().Authentication.User.Claims
그러나 시작 시 특히 ID를 재생성할 경우 "사용자 ID 생성 비동기" 메서드 내에 클레임을 추가하는 것이 좋습니다.Auth.cs 을 사용할 수 있습니다.
ControllerBase 클래스에 따라 작업을 실행하는 사용자에 대한 클레임을 가져올 수 있습니다.
여기 한 줄로 하는 방법이 있습니다.
var claims = User.Claims.ToList();
var claim = User.Claims.FirstOrDefault(c => c.Type == "claim type here");
저는 그것을 제 베이스 컨트롤러에서 그렇게 사용했습니다.바로 사용할 수 있도록 공유하는 것입니다.
public string GetCurrentUserEmail() {
var identity = (ClaimsIdentity)User.Identity;
IEnumerable<Claim> claims = identity.Claims;
var email = claims.Where(c => c.Type == ClaimTypes.Email).ToList();
return email[0].Value.ToString();
}
public string GetCurrentUserRole()
{
var identity = (ClaimsIdentity)User.Identity;
IEnumerable<Claim> claims = identity.Claims;
var role = claims.Where(c => c.Type == ClaimTypes.Role).ToList();
return role[0].Value.ToString();
}
언급URL : https://stackoverflow.com/questions/21404935/mvc-5-access-claims-identity-user-data
'programing' 카테고리의 다른 글
| SQL Server 2008 Management Studio에서 텍스트 또는 막대(MAX) 열의 전체 내용을 보려면 어떻게 합니까? (0) | 2023.04.27 |
|---|---|
| Bash의 조건부로 "아무것도 하지 않음"을 의미하는 명령어는 무엇입니까? (0) | 2023.04.27 |
| wpf에서 버튼 테두리를 완전히 제거하려면 어떻게 해야 합니까? (0) | 2023.04.27 |
| 빌드 경로 오류가 해결될 때까지 프로젝트를 빌드할 수 없습니다. (0) | 2023.04.27 |
| C# 데이터 테이블로 SQL 테이블 읽기 (0) | 2023.04.27 |
