Notice
Recent Posts
Recent Comments
Link
반응형
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| 8 | 9 | 10 | 11 | 12 | 13 | 14 |
| 15 | 16 | 17 | 18 | 19 | 20 | 21 |
| 22 | 23 | 24 | 25 | 26 | 27 | 28 |
Tags
- spring security
- netty
- AWS
- API
- NGINX
- postgis
- 컨퍼런스
- 보안
- Kotlin
- 인증
- 공동인증서
- Spring
- Mono
- 본인확인
- deepseek vs chatgpt
- Flux
- Spring Boot
- 딥시크
- 코틀린
- 허깅 페이스
- webflux
- ktlin
- exception
- IntelliJ
- docker
- 본인인증
- 로그인
- db
- PostgreSQL
- AOP
Archives
- Today
- Total
[수미수의 개발 브로구]
[WebFlux] Spring Security 적용 본문
반응형
들어가기 전
오늘은 WebFlux 에서 Spring Security 를 적용하여, Http Authorization Header 에서 Jwt Token 을 추출 하는 방법에 대해서 이야기 하고자 한다. 현재 모놀리식 구조에 MSA 로 전환하면서, 여러 서비스가 고객의 정보를 조회하기 위해, 고객 정보와 관련된 도메인은 WebFlux 로 프로젝트를 진행하였다. 여러 서비스들이 해당 WebFlux 프로젝트를 호출 할때, Http Authorization Header 의 Jwt 토큰 기반으로 호출 하였고, WebFlux 프로젝트는 Http header 로 부터 Berer Token 을 추출하여 인증 정보를 가져와야 했고, WebFlux 에서는 기존 MVC 와 다르게 설정을 해야했다.
따라하기
build.kt 설정
아래와 같이 build.kt 파일에 spring security 관련 프로젝트를 implementation 한다.
implementation("org.springframework.boot:spring-boot-starter-oauth2-resource-server")
implementation("org.springframework.boot:spring-boot-starter-security")
implementation("org.springframework.boot:spring-boot-starter-webflux")
testImplementation("org.springframework.security:spring-security-test")
Controller 구현
Http Authorization header의 Berer Token 을 검증하기 위해, @PreAuthorize() 어노테이션을 사용 하였다. 만약, 인증 서버와 통신 후 정상적인 토큰인 경우, 정의한 메서드 Flow 를 타게 된다.
class DetailContactController(
val detailContactService: DetailContactService
) {
@PostMapping("/get/customer/detail/contact")
@PreAuthorize("isAuthenticated()")
fun getCustomerDetailContact(): Mono<ResponseEntity<CustomerDetailContactResponse>> {
return ReactiveSecurityContextHolder.getContext()
.map {
ClientUtil.getCustomerIdFromToken(it)
}
.switchIfEmpty(Mono.defer { throw AuthenticationFailedException(
ApiResponseCode.NO_DATA,
CustomExceptionMessage.AUTHENTICATION_FAILED) })
.flatMap { detailContactService.getCustomerDetailContact(it) }
.map { s -> ResponseEntity(s, HttpStatus.OK) }
}
}
위 소스에서 Reactive 로 처리 하기 위해서, ReactiveSecurityContextHolder 객체를 사용하여, Context 정보를 불러온 뒤 map 을 통해서 Bearer Token 정보를 추출하여 처리 하였다.
반응형
'Language & Framework > WebFlux' 카테고리의 다른 글
| [WebFlux] Spring WebFlux 프로젝트 생성 하기 (0) | 2023.08.14 |
|---|---|
| [WebFlux] Spring WebFlux 원리 (2) | 2023.08.13 |
| [WebFlux] Spring WebFlux란? #1 (0) | 2023.08.13 |
| [WebFlux] WebFlux 적용기 (2) | 2023.08.09 |
| [WebFlux] AWS DynamoDB 설정 (1) | 2023.08.08 |