오래 못 할 짓 하지 않기

[ Spring boot Security ] 7. 로그인 성공 JWT 발급 본문

혼자하기/연습 1) OAuth

[ Spring boot Security ] 7. 로그인 성공 JWT 발급

쫑알bot 2024. 3. 3. 00:00
728x90

 

로그인에 성공했을 때, 실행되어야 하는 핸들러를 만들어서

내부에 JWT 발급을 구현한다.

 

 

Handler 내부 구현은 다음과 같다.

최종적으로 토큰을 발급할거니까 JWTUtil을 주입받아야하고

성공했다는 SimpleUrlAuthenticationSuccessHandler 를 상속받는다.

 

29번째 줄 : 로그인에 성공했다면 유저의 로그인 정보를 가져온다.

34,40번째 줄 : 로그인한 유저 정보에서 username, role을 가져온다.

43 번째 줄 : 그걸 기반으로 토큰을 만든다.

 

이걸 쿠키 형식으로 보내준다.

 

  

 

코드▼

 

더보기
package com.example.oauthtest.oauth;

import com.example.oauthtest.dto.CustomOAuth2User;
import com.example.oauthtest.jwt.JWTUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;

@Component
public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private final JWTUtil jwtUtil;
    public CustomSuccessHandler(JWTUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        //OAuth2User
        CustomOAuth2User customUserDetails = (CustomOAuth2User) authentication.getPrincipal();

        // username을 받고 role을 받아와서 JWT 메서드에 넘겨줄 예정이다.

        // username 받기
        String username = customUserDetails.getUsername();

        // role 받기
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        Iterator<? extends GrantedAuthority> iterator = authorities.iterator();
        GrantedAuthority auth = iterator.next();
        String role = auth.getAuthority();

        //받은 내용들로 토큰 생성
        String token = jwtUtil.createJwt(username, role, 60 * 60 * 60L);

        response.addCookie(createCookie("Authorization", token));
        response.sendRedirect("http://localhost:3000/");

    }

    private Cookie createCookie(String key, String value) {
        Cookie cookie = new Cookie(key, value);
        cookie.setMaxAge(60 * 60 * 60);
        cookie.setPath("/");
        cookie.setHttpOnly(true); // 자바 스크립트가 쿠키를 가져가지 못 함


        return cookie;
    }

}

 

이렇게 한 다음 securityConfig에서 다음과 같이 추가해준다.

 

 

코드▼

 

더보기
  //oauth2
        http
                .oauth2Login((oauth2) -> oauth2
                        .userInfoEndpoint((userInfoEndpointConfig) -> userInfoEndpointConfig
                                .userService(customOAuth2UserService)).successHandler(customSuccessHandler));