27. JWT를 위한 강제 로그인 진행
by 볼빵빵오춘기JwtAuthenticationFilter.java - attemptAuthentication() : username, password 받기. 코드 추가
코드 추가 - 방법1
@RequiredArgsConstructor public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter { private final AuthenticationManager authenticationManager; // login 요청을 하면 로그인 시도를 위해서 실행되는 함수 @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { System.out.println("JwtAuthenticationFilter login try"); // 1. username, password를 받는다 try{ System.out.println(request.getInputStream().toString()); }catch (IOException e){ e.printStackTrace(); } System.out.println("================="); // 2. 정상인지 로그인 시도를 해본다. // authenticationManager로 로그인 시도를 하면 PrincipalDetailsService가 호출이 된다. => loadUserByUsername()이 실행된다. // 3. PrincipalDetails를 세션에 담는다. (세션에 담는 이유는 권한관리를 하기 위해서이다.) // 4. JWT 토큰을 만들어서 응답해주면 된다. return null; } }
코드 추가 - 방법2
@RequiredArgsConstructor public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter { private final AuthenticationManager authenticationManager; // login 요청을 하면 로그인 시도를 위해서 실행되는 함수 @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { System.out.println("JwtAuthenticationFilter login try"); // 1. username, password를 받는다 try{ BufferedReader br = request.getReader(); String inputStr = null; while((inputStr=br.readLine())!= null){ System.out.println(inputStr); } }catch (IOException e){ e.printStackTrace(); } System.out.println("================="); // 2. 정상인지 로그인 시도를 해본다. // authenticationManager로 로그인 시도를 하면 PrincipalDetailsService가 호출이 된다. => loadUserByUsername()이 실행된다. // 3. PrincipalDetails를 세션에 담는다. (세션에 담는 이유는 권한관리를 하기 위해서이다.) // 4. JWT 토큰을 만들어서 응답해주면 된다. return null; } }
코드 추가 - 방법3 - 추가1
// 생략 // 1. username, password를 받는다 try{ ObjectMapper om = new ObjectMapper(); User user = om.readValue(request.getInputStream(), User.class); System.out.println(user); }catch (IOException e){ e.printStackTrace(); } // 생략
코드 추가 - 방법3 - 추가2
@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { // 코드 생략 try{ // 1. username, password를 받는다. ObjectMapper om = new ObjectMapper(); User user = om.readValue(request.getInputStream(), User.class); System.out.println(user); // 토큰 만들기 UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword()); // 2. 정상인지 로그인 시도를 해본다. // authenticationManager로 로그인 시도를 하면 PrincipalDetailsService가 호출이 된다. => loadUserByUsername()이 실행된다. // PrincipalDetailsService의 loadUserByUsername() 함수가 실행된다. // DB에 있는 username과 password가 일치한다. Authentication authentication = authenticationManager.authenticate(authenticationToken); // 일치하는지 확인하기 위한 코드일뿐 PrincipalDetails principalDetails = (PrincipalDetails) authentication.getPrincipal(); System.out.println("로그인 완료 확인 : "+principalDetails.getUser().getUsername()); // 값이 있다는건 로그인이 정상적으로 되었다는 뜻 // authentication 객체가 session 영역에 저장해야하고 그 방법이 return 해주면 된다. // 리턴 이유는 권한 관리를 security가 대신 해주기 때문에 편하려고 하는 것이다. // 굳이 JWT 토큰을 사용하면서 세션을 만들 필요x. But 근데 단지 권한 처리 때문에 session에 넣어 준다. // 3. PrincipalDetails를 세션에 담는다. (세션에 담는 이유는 권한관리를 하기 위해서이다.) // 밑에 authentication return 해줌으로서 PrincipalDetails를 세션에 담긴다. return authentication; // 4. JWT 토큰을 만들어서 응답해주면 된다. =>?? }catch (IOException e){ e.printStackTrace(); } // 코드 생략 return null; // try-catch문에서 실행되고 그것이 실패사면 로그인 정보가 일치하지않는것이기 때문에 null을 반환 }
RestApiController.java - BCryptPasswordEncoder타입 변수 추가
private final BCryptPasswordEncoder bCryptPasswordEncoder;
JwtAuthenticationFilter.java - successfulAuthentication() 오버라이드
@Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { System.out.println("successfulAuthentication run - 인증 완료"); super.successfulAuthentication(request, response, chain, authResult); }
실행결과
제대로 된 정보를 넣었을 경우

일부로 비번이나 아이디를 틀렸을 경우


블로그의 정보
Hello 춘기's world
볼빵빵오춘기