728x90
@Service
@Slf4j
@AllArgsConstructor
public class CustomUserServiceImp implements UserDetailsService {

  private final UserRepository userRepository;

  private final AuthoritiesRepository authoritiesRepository;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    User user = userRepository.findByUsername(username);
    if ("null".equals(user)) {
      throw new UsernameNotFoundException("not found user:" + username);
    }

    CustomUser customUser = new CustomUser();
    customUser.setUsername(user.getUsername());
    customUser.setPassword(user.getPassword());
    customUser.setAuthorities(getAuthorities(username));
    customUser.setEnabled(true);
    customUser.setAccountNonExpired(true);
    customUser.setAccountNonLocked(true);
    customUser.setCredentialsNonExpired(true);
    return customUser;
  }

  public Collection<GrantedAuthority> getAuthorities(String username) {
    List<Authority> authList = authoritiesRepository.findByUsername(username);
    List<GrantedAuthority> authorities = new ArrayList<>();
    for (Authority authority : authList) {
      authorities.add(new SimpleGrantedAuthority(authority.getAuthority()));
    }
    return authorities;
  }
}

내저장소 바로가기 luxury515

'Springboot3.0' 카테고리의 다른 글

[Interface]`UserDetails` 구현  (0) 2023.04.16
Springboot Security  (0) 2023.04.16
728x90
@Data
public class CustomUser implements UserDetails {
  private String username;
  private String password;
  private boolean isEnabled;
  private boolean isAccountNonExpired;
  private boolean isAccountNonLocked;
  private boolean isCredentialsNonExpired;
  private Collection<? extends GrantedAuthority> authorities;
}


내저장소 바로가기 luxury515

'Springboot3.0' 카테고리의 다른 글

[Interface]`UserDetailsService`  (0) 2023.04.16
Springboot Security  (0) 2023.04.16
728x90
@EnableWebSecurity
@Configuration
@AllArgsConstructor
public class SecurityConfig {

  private final CustomUserServiceImp customUserServiceImp;
  @Bean
  public BCryptPasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
  }

  @Bean
  public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.authorizeHttpRequests(
            (auth) ->
                auth.antMatchers("/user/**", "/auth/**").permitAll().anyRequest().authenticated())
        .httpBasic(withDefaults());
    http.headers()
            .frameOptions().sameOrigin();
    http.userDetailsService(customUserServiceImp);
    return http.build();
  }

  @Bean
  public WebSecurityCustomizer webSecurityCustomizer() {
    return (web -> web.ignoring().antMatchers("/images/**", "/js/**", "/webjars/**"));
  }
}


내저장소 바로가기 luxury515

'Springboot3.0' 카테고리의 다른 글

[Interface]`UserDetailsService`  (0) 2023.04.16
[Interface]`UserDetails` 구현  (0) 2023.04.16

+ Recent posts