BE/Spring in Action 5th

4장, 스프링 시큐리티

잠수함 2021. 11. 2. 09:41
728x90

4-1. 스프링 시큐리티 활성화하기

- 가장 먼저 스프링 부트 보안 스타터 의존성을 빌드 명세에 추가하는 것(pom.xml추가)

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

 

- 서버를 실행하고 접속을 하면 로그인 화면이 나옴

  ID: user

Password 는 console 화면에 나옴.

 

- 보안 스타터 프로젝트 빌드 파일에 추가했을시 보안구성

- 모든 HTTP 요청 경로는 인증되어야 한다.

- 어떤 특정 역할이나 권한이 없다

- 로그인 페이지가 따로 없다

- 스프링 시큐리티의  HTTP 기본인증을 사용해서 인증된다

- 사용자는 하나만 있으며, 이름은 user다. 비밀번호는 암호화 해준다.

 

4-2. 스프링 시큐리티 구성하기

 - securityconfig.class 의 역할 (간단히 말해서 사용자의 HTTP 요청 경로에 대해 접근 제한과 같은 보안 관련 처리를 우리가 원하는 대로 할 수 있게 해준다.)

package tacos.security;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
		.antMatchers("/design", "/orders")
		.access("hasRole('ROLE_USER')")
		.antMatchers("/", "/**").access("permitAll")
		.and().httpBasic();
	}
	
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.inMemoryAuthentication()
			.withUser("user1")
			.password("{noop}password1")
			.authorities("ROLE_USER")
			.and()
			.withUser("user2")
			.password("{noop}password2")
			.authorities("ROLE_USER");	
	}	

}