-
Notifications
You must be signed in to change notification settings - Fork 3
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
2 changed files
with
56 additions
and
2 deletions.
There are no files selected for viewing
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
48 changes: 48 additions & 0 deletions
48
backend/src/main/java/com/twtw/backend/config/socket/StompHandler.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,48 @@ | ||
package com.twtw.backend.config.socket; | ||
|
||
import com.twtw.backend.config.security.jwt.TokenProvider; | ||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.core.Ordered; | ||
import org.springframework.core.annotation.Order; | ||
import org.springframework.messaging.Message; | ||
import org.springframework.messaging.MessageChannel; | ||
import org.springframework.messaging.simp.stomp.StompCommand; | ||
import org.springframework.messaging.simp.stomp.StompHeaderAccessor; | ||
import org.springframework.messaging.support.ChannelInterceptor; | ||
import org.springframework.security.core.context.SecurityContextHolder; | ||
import org.springframework.stereotype.Component; | ||
|
||
import java.util.Optional; | ||
|
||
@Component | ||
@RequiredArgsConstructor | ||
@Order(Ordered.HIGHEST_PRECEDENCE + 99) | ||
public class StompHandler implements ChannelInterceptor { | ||
|
||
private static final String AUTHORIZATION_HEADER = "Authorization"; | ||
private static final String BEARER_PREFIX = "Bearer "; | ||
private final TokenProvider tokenProvider; | ||
|
||
@Override | ||
public Message<?> preSend(final Message<?> message, final MessageChannel channel) { | ||
final StompHeaderAccessor acessor = StompHeaderAccessor.wrap(message); | ||
|
||
if (StompCommand.CONNECT == acessor.getCommand()) { | ||
final Optional<String> headerValue = Optional.ofNullable(acessor.getFirstNativeHeader(AUTHORIZATION_HEADER)); | ||
resolveToken(headerValue).ifPresent(header -> { | ||
tokenProvider.validateToken(header); | ||
SecurityContextHolder.getContext().setAuthentication(tokenProvider.getAuthentication(header)); | ||
}); | ||
} | ||
return message; | ||
} | ||
|
||
private Optional<String> resolveToken(final Optional<String> headerValue) { | ||
return headerValue.map(header -> { | ||
if (header.startsWith(BEARER_PREFIX)) { | ||
return header.substring(7); | ||
} | ||
return header; | ||
}); | ||
} | ||
} |