-
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.
feat: Add JwtAuthenticationFilter (#3)
- Loading branch information
1 parent
aceda13
commit f6bea6c
Showing
1 changed file
with
45 additions
and
0 deletions.
There are no files selected for viewing
45 changes: 45 additions & 0 deletions
45
...oy-project/src/main/java/com/gdsc_teamb/servertoyproject/jwt/JwtAuthenticationFilter.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,45 @@ | ||
package com.gdsc_teamb.servertoyproject.jwt; | ||
|
||
import jakarta.servlet.FilterChain; | ||
import jakarta.servlet.ServletException; | ||
import jakarta.servlet.ServletRequest; | ||
import jakarta.servlet.ServletResponse; | ||
import jakarta.servlet.http.HttpServletRequest; | ||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.security.core.Authentication; | ||
import org.springframework.security.core.context.SecurityContextHolder; | ||
import org.springframework.util.StringUtils; | ||
import org.springframework.web.filter.GenericFilterBean; | ||
import java.io.IOException; | ||
|
||
|
||
@RequiredArgsConstructor | ||
public class JwtAuthenticationFilter extends GenericFilterBean { | ||
|
||
private final JwtTokenProvider jwtTokenProvider; | ||
|
||
@Override | ||
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { | ||
|
||
// Request Header 에서 JWT 토큰 추출 | ||
String token = resolveToken((HttpServletRequest) request); | ||
|
||
// validateToken 으로 토큰 유효성 검사 | ||
if (token != null && jwtTokenProvider.validateToken(token)) { | ||
// 토큰이 유효할 경우 토큰에서 Authentication 객체를 가지고 와서 SecurityContext에 저장 | ||
Authentication authentication = jwtTokenProvider.getAuthentication(token); | ||
// SecurityContextHolder에 인증 토큰 정보 세팅 | ||
SecurityContextHolder.getContext().setAuthentication(authentication); | ||
} | ||
chain.doFilter(request, response); | ||
} | ||
|
||
// Request Header 에서 JWT 엑세스 토큰 정보 추출 | ||
private String resolveToken(HttpServletRequest request) { | ||
String bearerToken = request.getHeader("Authorization"); | ||
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer")) { | ||
return bearerToken.substring(7); | ||
} | ||
return null; | ||
} | ||
} |