์๋ฌ ์ค๋ช
์๋ฐ ํ๋ก์ ํธ์์ ๋ก๊ทธ์ธ์ ๊ตฌํํ๊ธฐ ์ํด ์ํ๋ฆฌํฐ ํํฐ๋ฅผ ํตํด JWT ํ ํฐ์ ์์ฑํ๊ณ ํ์ธํ๋ ๊ณผ์ ์์ ์๊ธด ์๋ฌ

JwtAuthenticationFilter.java
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private final AuthenticationManager authenticationManager;
// /login ์์ฒญ์ ํ๋ฉด ์ฌ์ฉ์ ์ ๋ณด๋ฅผ ์ธ์ฆํ๊ธฐ ์ํด ์คํ๋๋ ํจ์
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
...์ฝ๋ ์๋ต...
}
// attemptAuthentication()์์ ์ธ์ฆ์ด ๋๋๋ฉด ์คํ๋๋ ํจ์
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
Authentication authResult) throws IOException, ServletException {
PrincipalDetails principalDetails = (PrincipalDetails) authResult.getPrincipal();
String jwtToken = JWT.create()
.withSubject(principalDetails.getUsername())
.withExpiresAt(new Date(System.currentTimeMillis() + (JwtProperties.EXPIRATION_TIME)))
.withClaim("id", principalDetails.getUser().getId())
.withClaim("username", principalDetails.getUser().getUsername())
.sign(Algorithm.HMAC256(JwtProperties.SECRET));
response.addHeader(JwtProperties.HEADER_STRING, JwtProperties.TOKEN_PREFIX + jwtToken);
}
}
JwtAuthorizationFilter.java
public class JwtAuthorizationFilter extends BasicAuthenticationFilter {
private UserRepository userRepository;
public JwtAuthorizationFilter(AuthenticationManager authenticationManager, UserRepository userRepository) {
super(authenticationManager);
this.userRepository = userRepository;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
String jwtHeader = request.getHeader(JwtProperties.HEADER_STRING);
if(jwtHeader == null || !jwtHeader.startsWith(JwtProperties.TOKEN_PREFIX)) {
chain.doFilter(request, response);
return;
}
String jwtToken = request.getHeader(JwtProperties.HEADER_STRING)
.replace(JwtProperties.TOKEN_PREFIX, "");
// ์๋ฌ๊ฐ ๋ฐ์ํ๋ ์์
String username = JWT.require(Algorithm.HMAC512(JwtProperties.SECRET))
.build()
.verify(jwtToken)
.getClaim("username").asString();
...์ฝ๋ ์๋ต...
}
}
ํด๊ฒฐ
๊ฒฐ๋ก ์ ๋งค์ฐ ๊ฐ๋จํ๋ค.
JWT ํ ํฐ์ ์ฒ์ ์์ฑํ๊ณ (JwtAuthenticationFilter.java) ๊ฒ์ฆํ๋(JwtAuthorizationFilter.java) ๋ ๊ณผ์ ์์ JWT ํ ํฐ ์๋ช ์ ์ ๊ทผํ ๋ ๊ฐ์ ์๊ณ ๋ฆฌ์ฆ์ ์ด์ฉํด์ผ ํ๋ ๊ฒ์ด์๋ค.
์์ JwtAuthenticationFilter.java ์ฝ๋๋ฅผ ๋ณด๋ฉด Algorithm.HMAC512๋ฅผ ์ด์ฉํด์ผ ํ๋๋ฐ ์ค์๋ก ๋ค๋ฅธ ์๊ณ ๋ฆฌ์ฆ(Algorithm.HMAC256)์ ๋ถ๋ฌ์ ํ ํฐ ์๋ช ํ ๊ฒ์ ํ์ธํ ์ ์๋ค. ๊ทธ๋์ ์๋ช ์ HMAC256์ผ๋ก ๋์ด ์๋๋ฐ ํ ํฐ ๊ฒ์ฆ ๊ณผ์ ์์๋ HMAC512๋ก ํ์ธํ๋๊น ์๋ชป๋ ์๊ณ ๋ฆฌ์ฆ์ ์ผ๋ค๋ ์๋ฌ๊ฐ ๋๋ ๊ฒ์ด์๋ค.
๋. :)
๋๊ธ