MyUserDetailsService
package com.daehan.shop.member;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@RequiredArgsConstructor
//DB에 있던 유저 정보 꺼내기
@Service
public class MyUserDetailsService implements UserDetailsService {
private final MemberRepository memberRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// DB에서 username을 가진 유저를 찾아와서
// return new User(유저아이디, 비번, 권한) 해주세요
var result = memberRepository.findByUsername(username);
if (result.isEmpty()) {
throw new UsernameNotFoundException("그런 아이디 없음");
}
var user = result.get();
//System.out.println(user);
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("일반유저"));
var a = new CustomUser(user.getUsername(), user.getPassword(), authorities);
a.displayName = user.getDisplayName();
return a;
}
}
***********************************************
SecurityConfig
package com.daehan.shop;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf((csrf) -> csrf.disable());
http.authorizeHttpRequests((authorize) ->
authorize.requestMatchers("/**").permitAll()
);
//나는 form으로 로그인하겠다
http.formLogin((formLogin) -> formLogin.loginPage("/login")
.defaultSuccessUrl("/") //로그인성공
// .failureUrl("/fail")
);
http.logout(logout -> logout.logoutUrl("/logout"));
return http.build();
}
}