728x90

 

Spring Security의 디펜던시

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <scope>test</scope>
</dependency>

 

시큐리티 설정 클래스

@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration {

	@Bean
	public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
			http.authorizeRequests()
			// 해당 url 패턴은 로그인 권한 없어도 접근 되도록
			.antMatchers("/public/**", "/member/form", "/member/join**")
			.permitAll()
			// 나머지 요청은 로그인을 해야 접근 되도록
			.anyRequest().hasRole("USER").and()
			// .csrf().disable() : ?
			.formLogin()
			.permitAll();
			
		return http.build();
	}
	
	/**
	 * 비밀번호 인코더 등록
	 * 등록안하면 There is no PasswordEncoder mapped for the id "null"에러가 발생함
	 * @return
	 */
	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}
	
	
}

 

MemberController에 추가한 내용

private final PasswordEncoder passwordEncoder;

String password = passwordEncoder.encode(form.getPassword());
// 암호화된 비밀번호로 저장
form.setPassword(password);

 

 

SecurityUserDetails implements UserDetails 생성

@Builder
@Data
public class SecurityUserDetails implements UserDetails{
	// 클래스명인 SecurityUserDetails 빨간줄 명령어 add unimplemented method 하면
	//  Collection<? extends GrantedAuthority> getAuthorities()
	// isAccountNonExpired()
	// isAccountNonLocked()
	// isCredentialsNonExpired()
	// isEnabled()
	// 추가됨
	
	private final int memberSeq;
	private final String username;
	private final String password;
	private final String nickname;
	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		// 권한을 추가해줘야 로그인 이후 오류 발생x
		return Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"));
	}
	@Override
	public boolean isAccountNonExpired() {
		return true;
	}
	@Override
	public boolean isAccountNonLocked() {
		return true;
	}
	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}
	@Override
	public boolean isEnabled() {
		return true;
	}
	
	
	
}

 

728x90
반응형

+ Recent posts