Java/인증 및 인가, IAM

[Java] Keycloak Admin REST API 기반 User 활용 및 예시 : with OpenFeign

adjh54 2025. 2. 23. 22:53
728x170
해당 글에서는 Keycloak Admin REST API를 기반으로 User 활용 방법 및 예시를 확인해 봅니다.





1) Keycloak Admin REST API : Users


💡 Keycloak Admin REST API : Users

- Users 엔드포인트는 사용자 관리를 위한 종합적인 REST API 인터페이스를 제공합니다.

- RESTful 아키텍처 원칙을 따르는 표준 HTTP 메서드 사용하며 JSON 형식의 요청/응답 데이터 구조를 가지고 있습니다.
- Bearer 토큰 기반의 인증 방식이며 페이지네이션과 필터링을 통한 효율적인 데이터 조회를 수행합니다.

 

 💡 [참고] 아래에서 다루지 않는 API에 대해서는 공식 API 문서를 참고하시면 도움이 됩니다.
 

Keycloak Admin REST API

POST /admin/realms/{realm}/clients/{client-uuid}/certificates/{attr}/download Get a keystore file for the client, containing private key and public certificate Parameters Path Parameters Name Description Default Pattern realm required realm name (not id!)

www.keycloak.org

 

1. 주요 기능


기능 분류 세부 기능
기본 CRUD 사용자 생성, 조회, 수정, 삭제
인증 관리 비밀번호 재설정, 임시 비밀번호 발급
세션 관리 로그아웃, 세션 무효화
권한 관리 사용자 그룹 및 역할 관리

 

 

 

2) 사용자 관리


💡 Users

- 사용자 관리와 관련된 다양한 작업을 수행할 수 있는 API를 제공합니다.
- 사용자 관리, 보안 및 인증 관리(비밀번호 재설정, 세션 관리), 권한 및 그룹 관리에 사용할 수 있습니다.
- 이러한 API들은 REST 방식으로 구현되어 있어 HTTP 메서드를 통해 직관적으로 사용할 수 있으며, JSON 형식으로 데이터를 주고받을 수 있습니다.
HTTP Method Endpoint 설명
GET /admin/realms/{realm}/users 사용자 목록 조회
POST /admin/realms/{realm}/users 새로운 사용자 생성
GET /admin/realms/{realm}/users/{id} 특정 사용자 정보 조회
PUT /admin/realms/{realm}/users/{id} 사용자 정보 업데이트
DELETE /admin/realms/{realm}/users/{id} 사용자 삭제
PUT /admin/realms/{realm}/users/{id}/reset-password 사용자 비밀번호 재설정
     
GET /admin/realms/{realm}/users/{id}/groups 사용자의 그룹 조회
PUT /admin/realms/{realm}/users/{id}/groups/{groupId} 사용자를 특정 그룹에 추가
GET /admin/realms/{realm}/users/{id}/role-mappings 사용자의 역할 매핑 조회
POST /admin/realms/{realm}/users/{id}/logout 사용자 세션 로그아웃
 

Keycloak Admin REST API

POST /admin/realms/{realm}/clients/{client-uuid}/certificates/{attr}/download Get a keystore file for the client, containing private key and public certificate Parameters Path Parameters Name Description Default Pattern realm required realm name (not id!)

www.keycloak.org

 

1. 사용자 목록 조회 및 필터링([GET] /admin/realms/{realm}/users)


💡 사용자 목록 조회 및 필터링([GET] /admin/realms/{realm}/users)

- 특정 realm의 모든 사용자 목록을 조회할 수 있습니다. 이 API는 페이지네이션과 필터링을 지원하여 대량의 사용자 데이터를 효율적으로 관리할 수 있습니다.

// format
// /admin/realms/{realm}/users

// example
// <http://localhost:9001/admin/realms/dev-realm/users?username=adjh54>

 

 

1.1. 요청 파라미터


💡 요청 파라미터

- realm 값을 제외한 파라미터들은 username=adjh54 형태로 전달을 합니다.
Parameter Type Required Description
realm string Yes 대상 Realm 이름
username string No 사용자명으로 필터링
email string No 이메일로 필터링
firstName string No 이름으로 필터링
lastName string No 성으로 필터링
first integer No 페이지네이션 시작 위치 (기본값: 0)
max integer No 반환할 최대 사용자 수 (기본값: 100)
enabled boolean No 활성화된 사용자만 필터링
briefRepresentation boolean No 간단한 사용자 정보만 반환 (기본값: true)
exact boolean No 정확한 매칭으로 검색 (기본값: false)
 /**
   * 전체 조회 및 필터링
   *
   * @param bearerToken
   * @return
   */
  @GetMapping("/users")
  List<UserRepresentation> selectKeycloakUserDetail(
          @RequestHeader("Authorization") String bearerToken,
          @RequestParam(value = "first", required = false) Integer first,
          @RequestParam(value = "max", required = false) Integer max,
          @RequestParam(value = "search", required = false) String search,
          @RequestParam(value = "username", required = false) String username,
          @RequestParam(value = "email", required = false) String email,
          @RequestParam(value = "enabled", required = false) Boolean enabled,
          @RequestParam(value = "exact", required = false) Boolean exact
  );

 

 

1.2. 응답


응답 값 타입 설명
id string 사용자 고유 식별자
username string 사용자 로그인 아이디
firstName string 사용자 이름
lastName string 사용자 성
email string 사용자 이메일 주소
emailVerified boolean 이메일 인증 여부
enabled boolean 계정 활성화 상태
totp boolean 2단계 인증 사용 여부
createdTimestamp long 계정 생성 시간
disableableCredentialTypes array 비활성화 가능한 자격 증명 유형
requiredActions array 필수 수행 작업 목록
notBefore integer 토큰 유효성 시작 시간
access object 사용자 접근 권한 설정
- manageGroupMembership: 그룹 멤버십 관리 권한
- view: 조회 권한
- mapRoles: 역할 매핑 권한
- impersonate: 사용자 대리 권한
- manage: 관리 권한

 

 

2. 새로운 사용자 생성([POST] /admin/realms/{realm}/users)


💡 새로운 사용자 생성([POST] /admin/realms/{realm}/users)

- 새로운 사용자를 생성하는 API입니다.
- 사용자의 기본 정보(사용자명, 이메일, 비밀번호 등)와 추가 속성을 설정할 수 있습니다.
- POST 메서드를 사용하며 JSON 형식으로 사용자 정보를 전달합니다.

// format
POST /admin/realms/{realm}/users

// example
POST <http://localhost:9001/admin/realms/dev-realm/users>

// request body
{
    "username": "newuser",
    "email": "newuser@example.com",
    "enabled": true,
    "firstName": "New",
    "lastName": "User",
    "credentials": [{
        "type": "password",
        "value": "password123",
        "temporary": false
    }]
}

 

 

2.1. 요청 파라미터


💡 요청 파라미터

- 해당 요청 정보는 import org.keycloak.representations.idm.UserRepresentation;를 import 하여서 해당 값들을 객체로 구성하여 요청합니다.
Parameter Type Required Description
username string Yes 사용자 로그인 아이디
email string No 사용자 이메일 주소
enabled boolean No 계정 활성화 여부
firstName string No 사용자 이름
lastName string No 사용자 성
credentials array No 사용자 인증 정보(비밀번호 등)
attributes object No 사용자 추가 속성
/**
 * 사용자 등록
 */
@PostMapping("/users")
void createUser(
        @RequestHeader("Authorization") String bearerToken,
        @RequestBody UserRepresentation userRepresentation
);

 

 

2.2. 응답


 💡 응답

- 성공적인 사용자 생성인 경우 201 Created 상태 코드가 반환됩니다.
응답 코드 응답 상태 Description
201 Created 성공적인 등록

 

 

 

3. 특정 사용자 정보 조회([GET] /admin/realms/{realm}/users/{id})


 💡 특정 사용자 정보 조회([GET] /admin/realms/{realm}/users/{id})

- 특정 사용자의 상세 정보를 조회하는 API입니다.
- 사용자 ID를 기반으로 해당 사용자의 모든 정보를 반환합니다.
- 사용자의 기본 정보, 속성, 그룹 멤버십 등을 확인할 수 있습니다.

// format
// /admin/realms/{realm}/users/{id}

// example
// http://localhost:9001/admin/realms/dev-realm/users/affe220c-b622-44d4-88d0-339bef7edff3

 

 

3.1. 요청 파라미터


Parameter Type Required Description
realm string Yes 대상 Realm 이름
id string Yes 조회할 사용자의 고유 식별자
/**
   * 아이디 기반 특정 사용자 조회
   */
  @GetMapping("/{id}}")
  void selectKeycloakUserDetail(
          @RequestHeader("Authorization") String bearerToken,
          @PathVariable String id
  );

 

 

3.2. 응답


💡 응답

- 성공적인 조회의 경우 200 OK 상태 코드와 함께 사용자 정보가 JSON 형식으로 반환됩니다.
- 사용자를 찾을 수 없는 경우 404 Not Found 상태 코드가 반환됩니다.
응답 코드 응답 정보 설명
200 OK 성공적인 조회
404 Not Found 조회 실패

 

 

4. 사용자 정보 수정([PUT] /admin/realms/{realm}/users/{id})


💡 사용자 정보 수정([PUT] /admin/realms/{realm}/users/{id})

- 기존 사용자의 정보를 업데이트하는 API입니다.
- 사용자의 기본 정보, 속성, 설정 등을 수정할 수 있습니다.
- PUT 메서드를 사용하며 JSON 형식으로 업데이트할 정보를 전달합니다.
// format
// [PUT] /admin/realms/{realm}/users/{id}

// example
// [PUT] http://localhost:9001/admin/realms/dev-realm/users/affe220c-b622-44d4-88d0-339bef7edff3

// request body
{
    "firstName": "Updated",
    "lastName": "User",
    "email": "updated@example.com",
    "enabled": true,
    "emailVerified": true,
    "attributes": {
        "customField": ["value"]
    }
}

 

 

 

4.1. 요청 파라미터


💡 요청 파라미터

- 해당 전송하는 파라미터의 경우는 id 값을 제외하고는 UserRepresentation 객체로 구성하여서 전달을 합니다.
Parameter Type Required Description
realm string Yes 대상 Realm 이름
id string Yes 수정할 사용자의 고유 식별자
username string No 사용자 로그인 아이디
email string No 사용자 이메일 주소
firstName string No 사용자 이름
lastName string No 사용자 성
enabled boolean No 계정 활성화 여부
emailVerified boolean No 이메일 인증 여부
attributes object No 사용자 추가 속성
 /**
   * 사용자 수정
   */
  @PutMapping("/users/{id}")
  void updateUser(
          @RequestHeader("Authorization") String bearerToken,
          @PathVariable String id,
          @RequestBody UserRepresentation userRepresentation
  );

 

 

4.2. 응답 


응답 코드 응답 설명 설명
204 No Content 성공적인 업데이트
404 Not Found 사용자를 찾을 수 없음
400 Bad Request 요청 본문이 유효하지 않음

 

 

 

5. 사용자 삭제([DELETE] /admin/realms/{realm}/users/{id})


💡 사용자 삭제([DELETE] /admin/realms/{realm}/users/{id})

- 특정 사용자를 시스템에서 삭제하는 API입니다. 삭제된 사용자는 복구할 수 없으며, 관련된 모든 데이터가 함께 삭제됩니다.
- DELETE 메서드를 사용합니다.

 

 

// format
// DELETE /admin/realms/{realm}/users/{id}

// example
// DELETE http://localhost:9001/admin/realms/dev-realm/users/affe220c-b622-44d4-88d0-339bef7edff3

 

 

5.1. 요청 파라미터


Parameter Type Required Description
realm string Yes 대상 Realm 이름
id string Yes 삭제할 사용자의 고유 식별자
/**
 * 사용자 삭제
 */
@DeleteMapping("/users/{id}")
void deleteUser(
        @RequestHeader("Authorization") String bearerToken,
        @PathVariable String id
);

 

 

5.2. 응답


응답 코드 응답 상태 설명
204 No Content 성공적인 삭제
404 Not Found 사용자를 찾을 수 없음

 

 

 

6. 사용자 비밀번호 재설정([PUT] /admin/realms/{realm}/users/{id}/reset-password)


💡 사용자 비밀번호 재설정([PUT] /admin/realms/{realm}/users/{id}/reset-password)

- 특정 사용자의 비밀번호를 재설정하는 API입니다.
- 임시 비밀번호를 설정하거나 영구 비밀번호로 변경할 수 있습니다.
- PUT 메서드를 사용하며 JSON 형식으로 새 비밀번호 정보를 전달합니다.

 

 

// format
// PUT /admin/realms/{realm}/users/{id}/reset-password

// example
// PUT http://localhost:9001/admin/realms/dev-realm/users/97204aa2-1160-4243-903b-81ba2be14de0/reset-password

// request body
{
    "type": "password",
    "value": "newPassword123",
    "temporary": false
}

 

 

6.1. 요청 파라미터


💡 요청 파라미터

- 해당 값은 id 값을 제외하고는 import org.keycloak.representations.idm.CredentialRepresentation; 를 import 하여서 객체를 구성하여 전달합니다.
Parameter Type Required Description
realm string Yes 대상 Realm 이름
id string Yes 비밀번호를 재설정할 사용자의 고유 식별자
type string Yes 인증 타입 (일반적으로 "password")
value string Yes 새로운 비밀번호
temporary boolean No 임시 비밀번호 여부 (true/false)
/**
 * 비밀번호 재설정
 *
 * @param bearerToken
 * @param credentialRepresentation
 */
@PutMapping("/users/{id}/reset-password")
void resetPassword(
        @RequestHeader("Authorization") String bearerToken,
        @PathVariable String id,
        @RequestBody CredentialRepresentation credentialRepresentation
);

 

 

6.2. 응답


응답 코드 응답 상태 설명
204 No Content 성공적인 비밀번호 재설정
404 Not Found 사용자를 찾을 수 없음
400 Bad Request 유효하지 않은 비밀번호 형식

 

 

 

 

7. 사용자 그룹 조회([GET] /admin/realms/{realm}/users/{id}/groups)


💡 사용자 그룹 조회([GET] /admin/realms/{realm}/users/{id}/groups)

- 특정 사용자가 속한 모든 그룹을 조회하는 API입니다.
- 사용자의 그룹 멤버십을 확인하고 관리하는 데 사용됩니다.
- GET 메서드를 사용하며 JSON 형식으로 그룹 정보를 반환합니다.
// format
// GET /admin/realms/{realm}/users/{id}/groups

// example
// GET http://localhost:9001/admin/realms/dev-realm/users/97204aa2-1160-4243-903b-81ba2be14de0/groups

 

 

7.1. 요청 파라미터


Parameter Type Required Description
realm string Yes 대상 Realm 이름
id string Yes 그룹을 조회할 사용자의 고유 식별자
/**
 * 사용자의 그룹 목록 조회
 */
@GetMapping("/users/{id}/groups")
List<GroupRepresentation> getUserGroups(
        @RequestHeader("Authorization") String bearerToken,
        @PathVariable String id
);

 

 

7.2. 응답


응답 코드 응답 상태 설명
200 OK 성공적인 그룹 목록 조회
404 Not Found 사용자를 찾을 수 없음

 

 

 

8. 사용자 그룹 추가([PUT] /admin/realms/{realm}/users/{id}/groups/{groupId})


💡 사용자 그룹 추가([PUT] /admin/realms/{realm}/users/{id}/groups/{groupId})

- 특정 사용자를 지정된 그룹에 추가하는 API입니다.
- 사용자의 그룹 멤버십을 관리하는데 사용됩니다.
- PUT 메서드를 사용하며 별도의 요청 본문이 필요하지 않습니다.
// format
// PUT /admin/realms/{realm}/users/{id}/groups/{groupId}

// example
// PUT http://localhost:9001/admin/realms/dev-realm/users/97204aa2-1160-4243-903b-81ba2be14de0/groups/f8293f24-5832-4841-9f23-b85e0c4c6e44

 

 

 

 

8.1. 요청 파라미터


Parameter Type Required Description
realm string Yes 대상 Realm 이름
id string Yes 그룹에 추가할 사용자의 고유 식별자
groupId string Yes 사용자를 추가할 그룹의 고유 식별자
/**
 * 사용자를 그룹에 추가
 */
@PutMapping("/users/{id}/groups/{groupId}")
void addUserToGroup(
        @RequestHeader("Authorization") String bearerToken,
        @PathVariable String id,
        @PathVariable String groupId
);

 

 

8.2. 반환 값


응답 코드 Status Code 설명
204 No Content 성공적인 그룹 추가
404 Not Found 사용자 또는 그룹을 찾을 수 없음

 

 

9. 사용자 역할 매핑 조회([GET] /admin/realms/{realm}/users/{id}/role-mappings)


💡 사용자 역할 매핑 조회([GET] /admin/realms/{realm}/users/{id}/role-mappings)

- 특정 사용자에게 할당된 모든 역할(role)을 조회하는 API입니다.
- 사용자의 권한과 접근 제어를 관리하는데 사용됩니다.
- GET 메서드를 사용하며 JSON 형식으로 역할 정보를 반환합니다.
// format
// GET /admin/realms/{realm}/users/{id}/role-mappings

// example
// GET http://localhost:9001/admin/realms/dev-realm/users/97204aa2-1160-4243-903b-81ba2be14de0/role-mappings

 

 

9.1. 요청 파라미터


Parameter Type Required Description
realm String Yes 대상 Realm 이름
id String Yes 역할을 조회할 사용자의 고유 식별자
/**
 * 사용자의 역할 매핑 조회
 */
@GetMapping("/users/{id}/role-mappings")
MappingsRepresentation getRoleMappings(
        @RequestHeader("Authorization") String bearerToken,
        @PathVariable String id
);

 

 

9.2. 반환 값


응답 코드 응답 상태 설명
200 OK 성공적인 역할 매핑 조회
404 Not Found 사용자를 찾을 수 없음

 

 

10. 사용자 로그아웃([POST] /admin/realms/{realm}/users/{id}/logout)


💡 사용자 로그아웃([POST] /admin/realms/{realm}/users/{id}/logout)

- 특정 사용자의 모든 활성 세션을 종료하는 API입니다.
- 강제 로그아웃이 필요한 경우나 보안상의 이유로 세션을 종료해야 할 때 사용됩니다.
- POST 메서드를 사용하며 별도의 요청 본문이 필요하지 않습니다.
// format
// POST /admin/realms/{realm}/users/{id}/logout

// example
// POST http://localhost:9001/admin/realms/dev-realm/users/97204aa2-1160-4243-903b-81ba2be14de0/logout

 

10.1. 요청 파라미터


Parameter Type Required Description
realm string Yes 대상 Realm 이름
id string Yes 로그아웃할 사용자의 고유 식별자
/**
 * 사용자 로그아웃
 */
@PostMapping("/users/{id}/logout")
void logoutUser(
        @RequestHeader("Authorization") String bearerToken,
        @PathVariable String id
);

 

 

10.2. 반환 값


응답 코드 응답 상태 설명
204 No Content 성공적인 로그아웃 처리
404 Not Found 사용자를 찾을 수 없음

 

 

 

 

 

 

오늘도 감사합니다 😀 

 

 

 

 

 

 

 

그리드형