JWT 토큰 발급은 로그인 성공 이후의 처리를 담당하는 successfulAuthentication
에서 해준다.
단, 발급만 해줄 뿐이지 클라이언트로부터 오는 JWT 토큰의 인증을 처리해주지는 않는다.
해당 부분은 필터를 만들어서 처리해야 한다.
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
//attemptAuthentication 실행 후 인증이 정상적으로 완료되면 successfulAuthentication 메서드가 실행된다.
//해당 메서드에서 jwt 토큰을 만들어서 요청한 사용자에게 jwt 토큰으로 응답해주면 된다.
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
PrincipalDetails principalDetails = (PrincipalDetails) authResult.getPrincipal();
//RSA 가 아닌 Hash 암호 방식이다.
String jwtToken = JWT.create()
.withSubject("cos token")//토큰 이름
.withExpiresAt(new Date(System.currentTimeMillis() + (60000 * 10)))//10분간 토큰 유효
.withClaim("id", principalDetails.getUser().getId())
.withClaim("username", principalDetails.getUser().getUsername())
.sign(Algorithm.HMAC512("cos"));
response.addHeader("Authorization","Bearer "+jwtToken);//Bearer 다음에 한 칸 띄워야 함.
}
}
POSTMan으로 요청해보면 리스폰스 헤더에 JWT 토큰이 적혀있다.