Keycloak과 Spring Boot 회원가입 로직 연동하기
이전 글에서는 Keycloak을 Docker로 실행하고 Spring Boot 프로젝트에 연동하는 기본적인 설정을 다루었습니다. 이번 글에서는 실제 회원가입 로직에서 어떻게 Keycloak과 연결되어 사용자를 생성하고 인증하는지, 그리고 이를 Spring Boot와 어떻게 매끄럽게 연결하는지를 실 예제를 기준으로 자세히 설명합니다.
1. 전반적인 흐름
- 사용자가 회원가입 양식 제출
- Spring Boot 서버에서 DB와 Keycloak 두 곳에 계정 정보 등록
- DB에는 사용자 상세 정보 저장 (ex. 이름, 전화번호, 카카오 여부)
- Keycloak에는 이메일과 비밀번호, 역할 정보 등을 저장
즉, 회원 정보는 Spring DB + Keycloak에 이중으로 저장됩니다.
2. 회원가입 로직 내부 구조
2-1. 사용자 요청 DTO 예시
{
"email": "user01@example.com",
"password": "qwer1234",
"nickname": "홍길동",
"phone": "01012345678"
}
2-2. Controller 흐름
@PostMapping("/register")
public ResponseEntity<?> register(@RequestBody UserDTO userDto) {
userService.registerUser(userDto);
return ResponseEntity.ok("회원가입 성공");
}
2-3. Service 내부
public void registerUser(UserDTO dto) {
// 1. DB 저장
UserEntity user = UserEntity.builder()
.email(dto.getEmail())
.password(passwordEncoder.encode(dto.getPassword()))
.nickname(dto.getNickname())
.phone(dto.getPhone())
.kakao(false)
.build();
userRepository.save(user);
// 2. Keycloak에 유저 등록
keycloakService.createKeycloakUser(dto.getEmail(), dto.getPassword(), "user");
}
2-4. KeycloakService 구현
public void createKeycloakUser(String email, String password, String role) {
Keycloak keycloak = getKeycloakInstance();
UserRepresentation user = new UserRepresentation();
user.setEnabled(true);
user.setUsername(email);
user.setEmail(email);
CredentialRepresentation credential = new CredentialRepresentation();
credential.setTemporary(false);
credential.setType("password");
credential.setValue(password);
user.setCredentials(Collections.singletonList(credential));
keycloak.realm("your-realm").users().create(user);
RoleRepresentation userRole = keycloak.realm("your-realm")
.roles()
.get(role)
.toRepresentation();
keycloak.realm("your-realm")
.users()
.get(getUserId(email, keycloak))
.roles()
.realmLevel()
.add(Collections.singletonList(userRole));
}
※ Keycloak 인스턴스는 관리자 인증 정보(client_id, secret 등)으로 초기화합니다.
3. Keycloak에서 확인 가능한 정보
- 사용자 생성 여부: Keycloak Admin Console → Users 탭
- 부여된 역할: Users → 선택 → Role Mappings
- 실제 로그인 테스트: Postman 또는 Keycloak 로그인 폼 사용
4. 보안 고려사항
- 비밀번호: DB에 저장할 때는 반드시
BCrypt
등의 암호화 적용 - Keycloak 권한: 클라이언트(client)의 access type이 confidential인지 public인지 설정 필요
- 에러 처리: Keycloak 사용자 생성 실패 시 rollback 로직 추가 권장
'Capstone-F5' 카테고리의 다른 글
Keycloak과 SpringSecurity (0) | 2025.06.20 |
---|---|
Keycloak과 SpringBoot 로그인 로직 연동 (0) | 2025.06.20 |
Docker에서 Keycloak 실행 및 오류 발생 원인 (0) | 2025.06.20 |
키클락 + SpringBoot 연동 방법 (0) | 2025.06.20 |
키클락(Keycloak)이란? (0) | 2025.06.20 |