스프링 시큐리티 Provider

greenTea·2023년 3월 20일

Provider

😎 Provider는 실질적으로 인증을 하는 곳으로 만약 성공한다면 Athentication 객체를 넘겨주면 된다. 기본 스프링 시큐리티에서는 UsernamePasswordAuthenticationToken 객체를 생성하여 보내준다.


@Service
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private UserRepository userRepository;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new BadCredentialsException("Invalid username or password"));

        if (!passwordEncoder().matches(password, user.getPassword())) {
            throw new BadCredentialsException("Invalid username or password");
        }

        List<GrantedAuthority> authorities = user.getRoles().stream()
                .map(role -> new SimpleGrantedAuthority(role.getName()))
                .collect(Collectors.toList());

        return new UsernamePasswordAuthenticationToken(username, password, authorities);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

- passwordEncoder()

😎 passwordEncoder란 사용자가 제출한 password를 암호화 해주는 메소드로 이 메소드를 사용하여 암호화하여 비밀번호를 저장한다. 보통 BCrypt를 사용한다.

- supports()

😊 해당 provider가 처리할 수 있는 authentication인지 확인하는 곳이다. 처리 할 수 없다면 다음 provider로 넘어가게 된다.

- authenticate()

👍 실질적으로 인증을 하는 곳으로 위에서는 repository를 이용하여 가져오고 있지만 보통은 userdetailservice를 이용하여 가져온다. 이 후 password를 검증하고 인증이 되었다면 authenticate객체에 담아 보낸다.

profile
greenTea입니다.

0개의 댓글