๋ฐ์ํ
์ด ํฌ์คํธ๋ ๋ฐ์ด ํ๋ก๊ทธ๋๋ฐ๋์ ์ ํ๋ธ ๊ฐ์๋ฅผ ๋ฃ๊ณ ๋์ ์ ๋ฆฌํ ๊ธ์ ๋๋ค.
Adapter ํจํด์ ์ด์ฉํ์ฌ UserDetails ๊ตฌํ
User ํด๋์ค๋ UserDetails๋ฅผ ๊ตฌํํ ํด๋์ค์ ๋๋ค.
์ฐ๋ฆฌ๋ Adapter ํจํด์ ์ด์ฉํ์ฌ User ํด๋์ค๋ฅผ ์์๋ฐ์ ๊ฒ์ ๋๋ค.
public class AccountAdapter extends User {
private Account account;
public AccountAdapter(Account account) {
super(account.getUsername(), account.getPassword(), getAuthorities(account.getRoles()));
this.account = account;
}
public static Collection<? extends GrantedAuthority> getAuthorities(Set<AccountRole> accountRoles) {
return accountRoles.stream()
.map(r -> new SimpleGrantedAuthority("ROLE_" + r))
.collect(Collectors.toList());
}
}
UserDeatilsService ๊ตฌํ
@Service
public class AccountService implements UserDetailsService {
@Autowired
private AccountRepository accountRepository;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Account account = accountRepository.findByUsername(username)
.orElseThrow(() -> new NotFoundException("Not Found User By username : " + username));
return new AccountAdapter(account); // AccountAdapter๋ User๋ฅผ ์์๋ฐ์๊ธฐ ๋๋ฌธ์ UserDetails ํ์
์ผ๋ก ์ฌ์ฉ ๊ฐ๋ฅ!
}
// ... Account ์ถ๊ฐ, ์ญ์ , ์์ ๋ก์ง
}
UsernamePasswordAuthenticationFilter ๊ตฌํ
public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private AuthenticationManager authenticationManager;
public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
// ๋ก๊ทธ์ธ ์ธ์ฆ์ ํ ๋, UserDetailsService์ loadUserByUsername()์ด ํธ์ถ์ด ๋๋ค.
}
}
- ์คํ๋ง ์ํ๋ฆฌํฐ ํํฐ์๋ ์ฌ์ฉ์ ์ธ์ฆ์ ํด์ฃผ๋ UsernamePasswordAuthenticationFilter๊ฐ ์๋ค.
- ๊ธฐ๋ณธ์ ์ผ๋ก POST "/login"์ผ๋ก ์์ฒญ์ด ๋ค์ด์ค๋ฉด ํด๋น ํํฐ๊ฐ ์์ฒญ์ ๊ฐ๋ก์ฑ์ ์ธ์ฆ์ ํฉ๋๋ค.
- ๊ทธ ๊ณผ์ ์์ attempAuthentication()๋ UserDetailsService์ loadUserByUsername()์ ํธ์ถํฉ๋๋ค.
๋ฐ์ํ