-
카테고리
-
세부 분야
백엔드
-
해결 여부
미해결
동작 방식
21.09.09 18:04 작성 조회수 353
0
안녕하세요 선생님! 훌륭한 강의 잘보고 있습니다.
해당 파트를 공부하는데 있어 스프링 시큐리티의 동작 방식이 궁금합니다.
1. 필터
http.authorizeRequests().antMatchers("/**")
.hasIpAddress("127.0.0.1") //<--ip
.and()
.addFilter(getAuthenticationFilter());
여기서 addFilter 메서드는 단순 welcome api를 요청하여도 필터가 동작하나요 아니면 로그인 할때만 필터가 동작하나요?
2. attemptAuthentication 메서드
//로그인 시도하면 가장 먼저 실행됨
@Override
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
try {
//전달되어진 inputStream 을 자바 클래스 파일로 변환
RequestLogin creds = new ObjectMapper().readValue(request.getInputStream(), RequestLogin.class);
//사용자가 입력한 값을 토큰으로 바꾸고 인증 처리를 하는 매니저에게 넘기면 아이디와 패스워드를 비교
//토큰 만듬
return getAuthenticationManager().authenticate(
//토큰으로 변환
new UsernamePasswordAuthenticationToken(
creds.getEmail(),
creds.getPassword(),
new ArrayList<>()
)
);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
로그인 시 가장 먼저 실행되는 메서드의 반환 값이 Authentication 객체인데, 그 객체가 아래 메서드에 사용되나요?
그 이유가 loadUseByUsername 메서드의 파라미터에 값을 넣어 준적이 없는 내부적으로 파라미터를 Authentication 객체의 값을 활용하나요?
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//순서 2
UserEntity findUser = userRepository.findByEmail(username);
if (findUser == null) {
throw new UsernameNotFoundException(username);
}
//User라는 객체로 success 메서드에서 사용 --> (User)authResult.getPrincipal()
return new User(findUser.getEmail(), findUser.getEncryptedPwd(),
true, true, true, true, new ArrayList<>());
}
로그인 시 순서:
1. attemptAuthentication 메서드 실행하여 Authentication(토큰) 객체 반환
2. loadUserByUsername 실행하여 Authentication 객체를 활용 하여 UserDetails 객체 반환
3. successfulAuthentication 실행하는데 UserDetails 객체 활용
가 맞나요..? 제가 나름 이해한대로 써봤습니다..
로그인 시 메서드의 호출 순서를 알고싶습니다. 또한 각 메서드의 반환 값이 서로 어떻게 연관이 있는지 궁금합니다.
spring security가 굉장히 어렵다고는 알고있는데.. 정리가 잘안되네요ㅜㅜ 두서 없이 쓴거같아 죄송합니다. 선생님의 강의를 보며 어제보다 나은 실력을 겸비하는거 같아 항상 감사합니다.
답변을 작성해보세요.
1
Dowon Lee
지식공유자2021.10.06
안녕하세요, 이도원입니다.
답변이 늦어 죄송합니다. 질문에 답변을 했었다고 생각했습니다.
문의 하신 내용에 간략히 답을 드리면,
1. UsernamePasswordAuthenticationFilter를 상속하는 AuthenticationFilter는 로그인 시 Spring Security에 의해 사용됩니다.
2. UsernamePasswordAuthenticationFilter -> AuthenticationManager -> AuthneticationProvider -> UserDetailService 순으로 사용됩니다.
3. 인증이 성공한 다음, successfulAuthentication 메소드에서 바로 결과를 반환해도 되지만, JWT를 생성하기 위해, UserService의 getUserByUserId 메소드를 호출하였습니다.
추가 궁금하신 점이 있으시면, 다시 글 남겨 주세요.
감사합니다.
답변 1