JWT 강제 로그인, 회원 가입 진행

dasd412·2022년 3월 15일
0

JWT

목록 보기
6/9

회원 가입 코드

회원 가입 시 password encoding을 해줘야 에러가 발생하지 않는다.

@RestController
@RequiredArgsConstructor
public class RestApiController {

  private final UserRepository userRepository;
  private final BCryptPasswordEncoder bCryptPasswordEncoder;

	@PostMapping("join")
    public String join(@RequestBody User user) {
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        user.setRoles("ROLE_USER");
        userRepository.save(user);
        return "회원가입완료";
    }
}

로그인 시도와 로그인 성공 이후의 코드

attemptAuthentication 호출 후 Authentication 객체를 리턴하게 되면 시큐리티 세션 영역에 저장된다. jwt 토큰을 사용하면 세션이 필요 없지만, 권한 관리를 시큐리티 세션이 알아서 해주기 때문에 편의를 위해 세션에 넣어주는 것이다.

attemptAuthentication 이 실행 종료되면 로그인 시도가 끝났다는 것이다. 만약 정상적으로 진행되었으면 successfulAuthentication 이 호출되어 로그인 성공 이후의 코드가 실행된다.

successfulAuthentication 내에서 jwt 토큰을 발급해준다.

@RequiredArgsConstructor
public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private final AuthenticationManager authenticationManager;

    //로그인 시도 할때 호출되는 메서드
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        System.out.println("로그인 시도중");
        try {
						//json parser를 이용해 request의 json을 읽어낸다.
            ObjectMapper om = new ObjectMapper(); //json parser
            User user = om.readValue(request.getInputStream(), User.class);
            System.out.println(user);

						//인증 토큰을 만든다.
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());

            //PrincipalDetailsService 의 loadUserByUsername()이 호출됨.
            //DB에 있는 Username과 password가 일치한다라는 뜻.
            Authentication authentication = authenticationManager.authenticate(authenticationToken);
						
            //authentication 객체가 session 영역에 저장됨. 로그인이 되었다는 뜻.
            //리턴의 이유는 권한 관리를 시큐리티 세션에게 위임하기 위해서다.
            //굳이 jwt 토큰을 사용하면서 세션을 만들 필요가 없지만 인가를 위해서 세션에 넣어주는 것이다.
            return authentication;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    //attemptAuthentication 실행 후 인증이 정상적으로 완료되면 successfulAuthentication 메서드가 실행된다.
    //해당 메서드에서 jwt 토큰을 만들어서 요청한 사용자에게 jwt 토큰으로 응답해주면 된다.
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        System.out.println("successfulAuthentication");
        super.successfulAuthentication(request, response, chain, authResult);
    }
}

구조

profile
시스템 아키텍쳐 설계에 관심이 많은 백엔드 개발자입니다. (Go/Python/MSA/graphql/Spring)

0개의 댓글