728x90
μλ¬ μ€λͺ
μλ° νλ‘μ νΈμμ λ‘κ·ΈμΈμ ꡬννκΈ° μν΄ μνλ¦¬ν° νν°λ₯Ό ν΅ν΄ 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λ‘ νμΈνλκΉ μλͺ»λ μκ³ λ¦¬μ¦μ μΌλ€λ μλ¬κ° λλ κ²μ΄μλ€.
λ. :)
λκΈ