웹서비스에 보안 적용

By | 2021년 7월 17일
Table of Contents

웹서비스에 보안 적용

목표

웹서비스에 로그인 체크 기능을 추가합니다.

프로젝트 생성

신규 프로젝트를 생성합니다.

의존성은 DevTools, Lombok, Spring Web, Thymeleaf 를 선택합니다.

파일 추가

home.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <title>Spring Security Example</title>
</head>
<body>
<h1>Welcome!</h1>

<p>Click <a th:href="@{/hello}">here</a> to see a greeting.</p>
</body>
</html>

hello.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org"
      xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
  <title>Hello World!</title>
</head>
<body>
<h1>Hello world!</h1>
</body>
</html>

MvcConfig.java

@Configuration
public class MvcConfig implements WebMvcConfigurer {

    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/home").setViewName("home");
        registry.addViewController("/").setViewName("home");
        registry.addViewController("/hello").setViewName("hello");
        registry.addViewController("/login").setViewName("login");
    }
}

프로젝트 실행

프로젝트를 실행합니다.

아무런 보안 기능없이 접속이 되는 것을 확인할 수 있습니다.

http://localhost:8080/

보안 적용

"/" 는 로그인 필요없이 접속 가능하게, "/hello" 는 로그인이 필요하도록 설정합니다.

우선, build.gradle 에 아래 의존성을 추가합니다.

implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.security:spring-security-test'

WebSecurityConfig.java

configure(HttpSecurity http) 에서 각각의 URL 에 대해 보안 적용여부를 정할 수 있습니다.

"/", "/home" 에 대해 전부 허용을 설정하고, 나머지 URL 을 전부 보안설정합니다.

마지막으로 로그인 페이지도 전부 허용으로 설정합니다.

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                    .antMatchers("/", "/home").permitAll()
                    .anyRequest().authenticated()
                    .and()
                .formLogin()
                    .loginPage("/login")
                    .permitAll()
                    .and()
                .logout()
                    .permitAll();
    }

    @Bean
    @Override
    public UserDetailsService userDetailsService() {
        UserDetails user =
                User.withDefaultPasswordEncoder()
                        .username("user")
                        .password("password")
                        .roles("USER")
                        .build();

        return new InMemoryUserDetailsManager(user);
    }
}

userDetailsService() 에서 사용자 로그인 정보를 설정해 줍니다.

login.html 을 추가합니다.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org"
      xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <title>Spring Security Example </title>
</head>
<body>
<div th:if="${param.error}">
    Invalid username and password.
</div>
<div th:if="${param.logout}">
    You have been logged out.
</div>
<form th:action="@{/login}" method="post">
    <div><label> User Name : <input type="text" name="username"/> </label></div>
    <div><label> Password: <input type="password" name="password"/> </label></div>
    <div><input type="submit" value="Sign In"/></div>
</form>
</body>
</html>

hello.html 을 수정합니다.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org"
      xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
  <title>Hello World!</title>
</head>
<body>
<h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
<form th:action="@{/logout}" method="post">
  <input type="submit" value="Sign Out"/>
</form>
</body>
</html>

2 thoughts on “웹서비스에 보안 적용

  1. Pingback: Spring Security with JDBC(UserDetailsService) – 상구리의 기술 블로그

  2. Pingback: Spring Boot 시작하기 – 상구리의 기술 블로그

답글 남기기