programing

ASP.NET ID에 클레임을 추가하는 방법

goodcopy 2021. 1. 19. 08:04
반응형

ASP.NET ID에 클레임을 추가하는 방법


ASP.NET ID를 사용하여 MVC 5의 사용자 ID에 사용자 지정 클레임을 추가하는 방법에 대한 문서 또는 예제를 찾으려고합니다. 이 예제는 OWIN 보안 파이프 라인에서 클레임을 삽입 할 위치와 폼 인증을 사용하여 쿠키에 클레임을 유지하는 방법을 보여줍니다.


아마도 다음 문서가 도움이 될 수 있습니다 :

var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, "Brock"));
claims.Add(new Claim(ClaimTypes.Email, "brockallen@gmail.com"));
var id = new ClaimsIdentity(claims,DefaultAuthenticationTypes.ApplicationCookie);

var ctx = Request.GetOwinContext();
var authenticationManager = ctx.Authentication;
authenticationManager.SignIn(id);

ASP.NET MVC 5 프로젝트 템플릿을 사용한다고 가정 할 때 클레임을 추가 할 올바른 위치는 ApplicationUser.cs. 을 검색하십시오 Add custom user claims here. 이것은 당신을 GenerateUserIdentityAsync방법으로 이끌 것 입니다. 이것은 ASP.NET Identity 시스템이 ApplicationUser 개체를 검색하고이를 ClaimsIdentity로 변환해야 할 때 호출되는 메서드입니다. 다음 코드 줄이 표시됩니다.

// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

그 후 주석입니다.

// Add custom user claims here

마지막으로 ID를 반환합니다.

return userIdentity;

따라서 사용자 지정 클레임을 추가하려는 경우 GenerateUserIdentityAsync다음과 같이 보일 있습니다.

// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

// Add custom user claims here
userIdentity.AddClaim(new Claim("myCustomClaim", "value of claim"));

return userIdentity;

등록시 사용자 지정 클레임을 추가하려면 다음 코드가 작동합니다.

            var user = new ApplicationUser
            {
                UserName = model.UserName,
                Email = model.Email
            };
            var result = await UserManager.CreateAsync(user, model.Password);
            // Associate the role with the new user 
            await UserManager.AddToRoleAsync(user.Id, model.UserRole);
            // Create customized claim 
            await UserManager.AddClaimAsync(user.Id, new Claim("newCustomClaim", "claimValue"));
            if (result.Succeeded)
            {...etc

WEB API C #에서 다음을 수행 할 수 있습니다.

var identity = new ClaimsIdentity(context.Options.AuthenticationType);          
        foreach(var Rol in roles)
        {
            identity.AddClaim(new Claim(ClaimTypes.Role, Rol));
        }
        identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
        identity.AddClaim(new Claim(ClaimTypes.Email, user.Correo));
        identity.AddClaim(new Claim(ClaimTypes.MobilePhone, user.Celular));
        identity.AddClaim(new Claim("FullName", user.FullName));
        identity.AddClaim(new Claim("Empresa", user.Empresa));
        identity.AddClaim(new Claim("ConnectionStringsName", user.ConnectionStringsName));

....

참조 URL : https://stackoverflow.com/questions/20383955/how-to-add-claims-in-asp-net-identity

반응형