인증 된 사용자의 역할 저장 / 할당
MVC를 사용하기 위해 사이트를 업그레이드하고 있으며 인증을 설정하는 가장 좋은 방법을 찾고 있습니다.
이 시점에서 Active Directory에서 로그인이 작동합니다. 사용자 이름과 암호를 확인한 다음 Auth 쿠키를 설정합니다.
사용자가 사이트를 탐색 할 때 컨트롤러가 해당 역할을 볼 수 있도록 로그인 할 때 사용자의 역할 정보를 저장하려면 어떻게해야합니까?
[Authorize(Roles = "admin")]
Active Directory에서 역할 목록을 가져 오는 데 문제가 없습니다. 컨트롤러가 볼 수 있도록 어디에 두어야할지 모르겠습니다.
사용자를 인증 할 때 새 GenericPrincipal 인스턴스를 생성합니다. 생성자는 사용자의 역할 인 문자열 배열을받습니다. 이제 HttpContext.Current.User를 일반 보안 주체와 동일하게 설정하고 인증 쿠키를 작성하면됩니다.
역할은 HttpContext 의 IPrincipal 에 추가됩니다 . GenericPrincipal을 만들고 생성자에서 역할 목록을 구문 분석하고 HttpContext.User로 설정할 수 있습니다. GenericPrincipal은 User.IsInRole("role")
또는 [Authorize(Roles="role")]
속성을 통해 액세스 할 수 있습니다.
이를 수행하는 한 가지 방법 (C #에서)은 인증 티켓을 만들 때 사용자 데이터 매개 변수에 쉼표로 구분 된 문자열로 역할을 추가하는 것입니다.
string roles = "Admin,Member";
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
userId, //user id
DateTime.Now,
DateTime.Now.AddMinutes(20), // expiry
false, //do not remember
roles,
"/");
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(authTicket));
Response.Cookies.Add(cookie);
그런 다음 인증 티켓에서 역할 목록에 액세스하고 Global.asax.cs에서 GenericPrincipal을 만듭니다.
protected void Application_AuthenticateRequest(Object sender, EventArgs e) {
HttpCookie authCookie =
Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null) {
FormsAuthenticationTicket authTicket =
FormsAuthentication.Decrypt(authCookie.Value);
string[] roles = authTicket.UserData.Split(new Char[] { ',' });
GenericPrincipal userPrincipal =
new GenericPrincipal(new GenericIdentity(authTicket.Name),roles);
Context.User = userPrincipal;
}
}
MVC 4 이상을 사용하는 경우 David Glenn의 답변을 사용할 때 Jaroslaw Waliszko의 조언을 따라야합니다.
"ASP.NET MVC 4에서 테스트했으며 대신 Application_PostAuthenticateRequest를 사용하는 것이 좋습니다. 그렇지 않으면 일반 보안 주체가 무시됩니다." – Jaroslaw Waliszko 9 월 7 일 16:18
따라서 위에서 언급했듯이이 작업을 수행하려면 Application_AuthenticateRequest 메서드 이름을 Application_PostAuthenticateRequest로 바꾸면됩니다. 나를 위해 매력처럼 일했다! 내가 Jaroslaw와 David를 찬성 할 수 있다면 그렇게 할 것입니다.
사용자 지정 역할 공급자를 만드는 경향이 있습니다. 여기에 예 :
Could you not drop in either an authorization store role manager or find (e.g. on Codeplex) or write another Role Provider that works with Active Directory to get the groups information?
This would save you the hassle of authenticating the user, getting their roles, and then re-passing that information into the constructor, and would all happen automatically for you as part of the framework.
ReferenceURL : https://stackoverflow.com/questions/1822548/store-assign-roles-of-authenticated-users
'developer tip' 카테고리의 다른 글
JavaScript 라이브러리를 최소화하고 압축하기 위해 무엇을 사용합니까? (0) | 2021.01.10 |
---|---|
Ruby XML to JSON 변환기? (0) | 2021.01.10 |
document.getElementById (id) .focus ()가 firefox 또는 chrome에서 작동하지 않습니다. (0) | 2021.01.09 |
빠르고 간단한 해시 코드 조합 (0) | 2021.01.09 |
Android에서 비트 맵을 그레이 스케일로 변환 (0) | 2021.01.09 |