34.5.8 역할 기반 인증

    특정 그룹(Group) 또는 역할(Role)에 따라서 권한을 주고자 할 때는 정책 기반으로 인증과 권한을 부여할 수 있다. 로그인 시 "Role" 값을 "Users"로 부여하면 해당 사용자는 Users 권한(Policy)을 받는다. 다음 코드 블록에서 RoleUsers 값을 주는 식으로 사용된다.

    ▼  UserController.cs 파일의 Login 액션 메서드의 코드 일부

    // [User][6][6] : 로그인 처리
    [HttpPost]
    [AllowAnonymous]
    public async Task<IActionResult> Login(
      UserViewModel model, string returnUrl = null)
    {
      if (ModelState.IsValid)
      {
          if (_repository.IsCorrectUser(model.UserId, model.Password))
          {
              // [!] 인증 부여
              var claims = new List<Claim>()
              {
                  // 로그인 아이디 지정
                  new Claim(“UserId”, model.UserId),
                  
                  // 기본 역할 지정, “Role” 기능에 “Users” 값 부여
                  new Claim(ClaimTypes.Role, “Users”) // 추가 정보 기록
              };
              
              var ci = new ClaimsIdentity(claims, model.Password);
              
              await HttpContext.Authentication.SignInAsync(
                  “Cookies”, new ClaimsPrincipal(ci));
              
              return LocalRedirect(”/User/Index”);
          }
      }
      
      return View(model);
    }
    

    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.