This repository has been archived by the owner on Nov 27, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
39 additions
and
0 deletions.
There are no files selected for viewing
39 changes: 39 additions & 0 deletions
39
src/main/java/com/example/daemawiki/global/security/JwtWebFilter.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
package com.example.daemawiki.global.security; | ||
|
||
import org.springframework.http.HttpHeaders; | ||
import org.springframework.http.server.reactive.ServerHttpRequest; | ||
import org.springframework.security.core.Authentication; | ||
import org.springframework.security.core.context.ReactiveSecurityContextHolder; | ||
import org.springframework.web.server.ServerWebExchange; | ||
import org.springframework.web.server.WebFilter; | ||
import org.springframework.web.server.WebFilterChain; | ||
import reactor.core.publisher.Mono; | ||
|
||
public class JwtWebFilter implements WebFilter { | ||
private final Tokenizer tokenizer; | ||
|
||
public JwtWebFilter(Tokenizer tokenizer) { | ||
this.tokenizer = tokenizer; | ||
} | ||
|
||
@Override | ||
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { | ||
return resolveToken(exchange.getRequest()) | ||
.flatMap(token -> { | ||
if (tokenizer.verify(token)) { | ||
Authentication authentication = tokenizer.getAuthentication(token); | ||
return chain.filter(exchange) | ||
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication)); | ||
} else { | ||
return chain.filter(exchange); | ||
} | ||
}); | ||
} | ||
|
||
private Mono<String> resolveToken(ServerHttpRequest request) { | ||
return Mono.justOrEmpty(request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION)) | ||
.filter(authHeader -> authHeader.startsWith("Bearer ")) | ||
.map(authHeader -> authHeader.substring(7)); | ||
} | ||
|
||
} |