Springboot

[Springboot] Security

KJihun 2023. 7. 1. 17:52
728x90

 

 

 

어제 Security가 Controller보다 먼저 실행된다는 것을 알았다.

하지만 오늘 직접 코드를 구현해 봄으로써 어떻게 Controller 이전에 Security가 올 수 있는지 확실히 알지 못했기에

login 기능을 구현하는데에 어려움을 겪었다. 찾아보던 도중, 좋은 notion글이 있어서 참조했다. 

 

 

Spring Security

인증(Authentication): 해당 사용자가 본인이 맞는지 확인하는 과정

hyeonjunju.notion.site

 

 

 

클라이언트가 정보를 요청하면 AuthenticationFilter가 요청을 가로채고, 가로챈 정보를 통해 토큰을 생성한다.

 

AuthenticationFilter 예시코드

    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        log.info("로그인 시도");
        try {
            LoginRequestDto requestDto = new ObjectMapper().readValue(request.getInputStream(), LoginRequestDto.class);

            return getAuthenticationManager().authenticate(
                    new UsernamePasswordAuthenticationToken(
                            requestDto.getUsername(),
                            requestDto.getPassword(),
                            null
                    )
            );
        } catch (IOException e) {
            log.error(e.getMessage());
            throw new RuntimeException(e.getMessage());
        }