[Spring Boot #29] 스프링 부트 시큐리티

2021. 3. 25. 01:34 Spring Framework/Spring boot2

| 스프링 부트 시큐리티

 

스프링 부트에서는 웹 접근 시 로그인 같은 인증과정을 쉽게 구현할 수 있도록 시큐리티 모듈을 제공합니다. 

 

| 스프링 부트 시큐리티 연동하기

 

의존성 추가

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

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

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

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

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <version>${spring-security.version}</version>
        <scope>test</scope>
    </dependency>
</dependencies>

 

프로젝트 구조

├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │       └── tutorial
│   │   │           └── spring
│   │   │               ├── Application.java
│   │   │               ├── HomeController.java
│   │   │               └── WebSecurityConfig.java
│   │   └── resources
│   │       ├── application.properties
│   │       ├── static
│   │       └── templates
│   │           ├── hello.html
│   │           ├── index.html
│   │           └── my.html
│   └── test
│       └── java
│           └── com
│               └── tutorial
│                   └── spring
│                       └── HelloControllerTest.java

 

테스트 코드

@RunWith(SpringRunner.class)
@WebMvcTest(HomeController.class)
public class HelloControllerTest {

    @Autowired
    MockMvc mockMvc;

    @Test
    public void hello_without_user() throws Exception {
        mockMvc.perform(get("/hello"))
                .andDo(print())
                .andExpect(status().isUnauthorized());
    }

    @Test
    @WithMockUser
    public void hello() throws Exception {
        mockMvc.perform(get("/hello"))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(view().name("hello"));
    }

    @Test
    @WithMockUser
    public void my() throws Exception {
        mockMvc.perform(get("/my"))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(view().name("my"));
    }
}
  • hello_without_user 테스트는 /hello 요청을 보낼 시 인증되지 않았다는 http status 코드(401)이 오는 것을 확인합니다.
  • hello와 my 테스트는 각각 @WithMocvUser 어노테이션을 사용하여 실제 클라이언트에서 요청하는 것을 테스트하는 것이 아닌 Mock을 가지고 테스트합니다. 따라서 인증과정을 거칠 필요없이 바로 필요한 기능을 테스트 할 수 있습니다.

Html 코드

<!--hello.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>Hello</h1>
</body>
</html>
<!--index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>Welcome</h1>
    <a href="/hello">Hello</a>
    <a href="/my">My</a>
</body>
</html>
<!--my.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>My</h1>
</body>
</html>

 

소스 코드

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}
@Controller
public class HomeController {

    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

    @GetMapping("/my")
    public String my(){
        return "my";
    }
}
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

}

 

  • WebSecurityConfigurerAdapter를 상속하여 시큐리티 관련 정보를 설정할 수 있습니다. 만일 별다른 설정 정보가 없다면 시큐리티 모듈에서 제공하는 기본 인증과정을 웹 어플리케이션에서 사용하게 됩니다.
  • 인증과정은 기본적으로는 formLogin과 http 인증과정을 거치게 됩니다.

 

결과화면

 

 

기본 인증과정 정보(로그인 아이디 및 패스워드)는 유저네임은 user, 패스워드는 아래 콘솔창에 출력되는 패스워드를 쓰면 됩니다.

Using generated security password: a258b433-c56e-4143-8cdd-d1fa7c58ac3c

 

 

 

참고자료 : https://www.inflearn.com/course/스프링부트



출처: https://engkimbs.tistory.com/798?category=767865 [새로비]