package springSecurity.demo.config;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
@Configuration // IoC 빈(bean)을 등록
public class SecurityConfig {
// 해당 메서드의 리턴되는 오브젝트를 ioC로 등록해준다.
@Bean
public BCryptPasswordEncoder encodePwd(){
return new BCryptPasswordEncoder();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests()
.antMatchers("/user/**").authenticated()
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_USER')") // 인증만 되면 들어갈 수 있는 주소
.antMatchers("/manager/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_USER')")
.anyRequest().permitAll()
.and()
.formLogin()
.loginPage("/loginForm")
.loginProcessingUrl("/login") // login 주소가 호출이 되면 시큐리티가 낚아채서 대신 로그인을 진행해준다.
.defaultSuccessUrl("/"); // 로그인이 완성되면 메인페이지로
return http.build();
}
}
package springSecurity.demo.config.auth;
import org.springframework.beans.factory.annotation.Autowired;
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 springSecurity.demo.model.User;
import springSecurity.demo.repository.UserRepository;
import java.util.Optional;
// 시큐리티 설정에서 loginProcessingUrl("/login");
// /login 요청이 오면 자동으로 UserDetailsService 타입으로 ioC되어있는 loadUserByUsername 함수가 실행
@Service
public class PrincipalDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
//시큐리티 session = Authentication = UserDetails
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User userEntity = userRepository.findByUsername(username);
if (userEntity != null) {
return new PrincipalDetails(userEntity);
}
return null;
}
}
package springSecurity.demo.config.auth;
// 시큐리티가 /login 주소 요청이 오면 낚아채서 로그인을 진행시킨다.
// 로그인을 진행이 완료가 되면 시큐리티 session을 만들어준다. (Security ContextHolder)
// 오브젝트 ==> Authentication 타입 객체
// Authentication 안에 User정보가 있어야 된다.
// User오브젝트타입 => UserDetails 타입 객체
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import springSecurity.demo.model.User;
import java.util.ArrayList;
import java.util.Collection;
// Security Session -> Authentication => UserDetails(PrincipalDetails)
public class PrincipalDetails implements UserDetails {
private User user; //콤포지션
public PrincipalDetails(User user){
this.user = user;
}
//해당 User의 권한을 리턴하는 곳
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Collection<GrantedAuthority> collect = new ArrayList<>();
collect.add(new GrantedAuthority() {
@Override
public String getAuthority() {
return user.getRole();
}
});
return collect;
}
@Override
public String getPassword() {
return user.getPassword();
}
@Override
public String getUsername() {
return user.getUsername();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
// 우리 사이트에서 1년동안 회원이 로그인을 안하면 휴먼 계정으로 하기로 함.
return true;
}
}
이번 파트는 좀 어려운 내용이 많다;;
흠,, 다시공부해야 하는 파트
'백엔드 > 스프링시큐리티연습' 카테고리의 다른 글
스프링부트 시큐리티 8강 - Authentication객체가 가질수 있는 2가지 타입 (0) | 2023.05.11 |
---|---|
스프링부트 시큐리티 3강 - 시큐리티 회원가입 (0) | 2023.04.26 |