๐Ÿ’ Spring/Spring Security

10. JWT ๋กœ๊ทธ์ธ์„ ์œ„ํ•œ UserDetails, UserDetailsService ๊ตฌํ˜„ํ•˜๊ธฐ

iseunghan 2021. 11. 2. 00:16
๋ฐ˜์‘ํ˜•

์ด ํฌ์ŠคํŠธ๋Š” ๋ฐ์–ด ํ”„๋กœ๊ทธ๋ž˜๋ฐ๋‹˜์˜ ์œ ํŠœ๋ธŒ ๊ฐ•์˜๋ฅผ ๋“ฃ๊ณ  ๋‚˜์„œ ์ •๋ฆฌํ•œ ๊ธ€์ž…๋‹ˆ๋‹ค.

 

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()์„ ํ˜ธ์ถœํ•ฉ๋‹ˆ๋‹ค.
๋ฐ˜์‘ํ˜•