web/Backend

[SpringBoot] KeyCloak 으로 인증서버 만들기(1)

뽀리님 2025. 5. 29. 15:44

현 회사에서 기능설계 아키텍처 및 표준화설계를 하면서 내부 서버에 SSO 인증 서비스를 만들고자 정리해보는 글이다.

 

1. 먼저 Keycloak을 설치하자.

https://ssmyefrin.tistory.com/98

 

[Docker] 도커로 Keycloak 설치하기(windows)

✔ Keycloak ?Keycloak은 Red Hat에서 개발한 오픈 소스 싱글 사인온(SSO) 및 ID 관리 플랫폼으로, 사용자 인증 및 권한 부여를 처리하는 솔루션이다. Keycloak은 다양한 기능을 제공하여 개발자가 보안 및

ssmyefrin.tistory.com

 

 

2. http://localhost:8080/ 로 접속해보자.

아래와 같은 화면에서 

 

Administration Console로 접속후 아까 docker 실행시 설정했던 ID/PW를 적어준다 (admin/1234)

 

그럼 다음과 같은 화면이 뜬다.

 

 

 

우선 Realm을 먼저 생성해주자

Realm이란 SSO 범위 설정 단위(회사마다, 시스템마다)라 보면 된다.

한 Realm내의 Client들(Application)은 서로 SSO를 공유할 수 있다.

 

 

 

1. Realm 생성

 

My_Realm 생성해준다

 

2. Client 추가

Client는 Keycloak에 등록되는 애플리케이션이다.(Spring Boot 서버가 여기 해당된다.)

 

Client authentication 을 활성화시켜야지 Spring Boot 에서 client-secret 로 접속을 할 수 있다.

생성 한 뒤 Credentials 탭으로 가면 secret 값을 볼 수 있다.

 

 

그런다음 auth-service에 간단하게 applcation.properties 설정을 해준다.

# --- JWT 검증 (리소스 서버) ---
spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:8080/realms/My_Realm

# --- OAuth2 Client (토큰 요청용) ---
spring.security.oauth2.client.registration.keycloak.client-id=auth-service
spring.security.oauth2.client.registration.keycloak.client-secret=입력
spring.security.oauth2.client.registration.keycloak.authorization-grant-type=client_credentials
spring.security.oauth2.client.registration.keycloak.scope=openid

spring.security.oauth2.client.provider.keycloak.issuer-uri=http://localhost:8080/realms/My_Realm

 

그런다음 간단히 Controller를 만들어줬다.

public class AuthController {
    @GetMapping("/validate")
    public ResponseEntity<?> validate(@AuthenticationPrincipal Jwt jwt) {
        try {
            String userId = jwt.getSubject(); // sub claim
            String email = jwt.getClaimAsString("email");
            String preferredUsername = jwt.getClaimAsString("preferred_username");
            List<String> roles = jwt.getClaimAsStringList("realm_access.roles"); // Keycloak에 따라 달라질 수 있음

            UserInfo userInfo = new UserInfo(userId, email, preferredUsername, roles);
            return ResponseEntity.ok(userInfo);
        } catch (Exception e) {
            log.error("[EXCEPTION]:"+e.getMessage(),e);
            return null;
        }
    }
}

 

 

 

🔹Postman 으로 접속해서 테스트해보자.

 

1. 토큰발급받기

Keycloak의 /token 엔드포인트는 OAuth 2.0 표준에 따라 동작하며,Content-Type: application/json은 지원하지 않기 때문에 header에 Content-Type을 application/x-www-form-urlencoded 로 설정해주어야 한다.

 

http://localhost:8080/realms/My_Realm/protocol/openid-connect/token 로 쏴보자

 

 

 

토큰값을 잘 불러오면 해당토큰으로 auth서비스를 호출해보자.

 

2. Auth서비스 호출

http://localhost:8081/auth/validate

 

 

 

잘되는걸 확인할 수가 있다.