1. 스프링 부트 프로젝트 생성
먼저, Spring Initializer를 사용하여 스프링 부트 프로젝트를 생성합니다. https://start.spring.io/ 에서 아래와 같이 프로젝트 설정을 입력한 후, "Generate" 버튼을 클릭하여 다운로드 받습니다.
- Project: Gradle Project
- Language: Java
- Spring Boot: 2.5.2 버전 사용
- Packaging: Jar
- Dependencies: Spring Web, Thymeleaf, Spring Security
2. 보안 설정 클래스 생성
SecurityConfig 클래스를 생성하여 간단한 보안 설정을 추가합니다.
SecurityConfig.java
package com.security.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.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public UserDetailsService userDetailsService() {
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
UserDetails user = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();
manager.createUser(user);
return manager;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.defaultSuccessUrl("/secure") // 로그인 성공 후의 기본 URL 지정
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.permitAll();
}
}
처음에 Spring Initializer 생성할 때 스프링 부트 버전 3.2.0으로 생성하여 최신 버전이라 WebSecurityConfigurerAdapter extends 상속 부분에 취소선 또는 에러가 발생할 것입니다.
public class SecurityConfig extends WebSecurityConfigurerAdapter {
SpringSecurity 5.7에서는 WebSecurityConfigurerAdapter를 더 이상 지원하지 않기 때문 build.gradle 에서 스프링부트 버전을 2.5.2 로 변경해줍니다.
build.gradle
plugins {
id 'java'
id 'org.springframework.boot' version '2.5.2'
id 'io.spring.dependency-management' version '1.1.0'
}
group = 'com.security'
version = '0.0.1-SNAPSHOT'
java {
sourceCompatibility = '17'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'
}
tasks.named('test') {
useJUnitPlatform()
}
3. 간단한 웹 애플리케이션 구현
간단한 웹 애플리케이션을 만들기 위해 컨트롤러와 Thymeleaf 템플릿을 작성합니다.
HomeController.java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HomeController {
@GetMapping("/")
public String home() {
return "home";
}
@GetMapping("/login")
public String login() {
return "login";
}
@GetMapping("/secure")
public String secure() {
return "secure";
}
}
HomeController
4. HTML 템플릿 작성
src/main/resources/templates 디렉토리에 Thymeleaf 템플릿을 작성합니다.
home.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<body>
<h2>Welcome to the Home Page!</h2>
<p><a th:href="@{/login}">Login</a></p>
</body>
</html>
login.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h2>Login Page</h2>
<form th:action="@{/login}" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required autofocus>
<br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<br>
<button type="submit">Login</button>
</form>
</body>
</html>
secure.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Secure Page</title>
</head>
<body>
<h2>Welcome to the Secure Page!</h2>
<p><a th:href="@{/logout}">Logout</a></p>
</body>
</html>
5. 실행
프로젝트를 빌드하고 실행하여 http://localhost:8080/ 에 접속하여 실습을 진행해보세요. home 페이지에서 Login 링크를 통해 로그인하면 secure 페이지로 이동할 수 있습니다. 로그아웃은 secure 페이지에서 가능합니다.
위 그림과 같이 컴파일 오류가 나오면 IntelliJ IDEA -> Settings -> Build Tools -> Gradle ->
Build and run using , Run tests using -> ItelliJ IDEA 변경
Gradle JVM -> 자바 버전 설정
하면 해결됩니다.
첫 화면
로그인 화면
SecurityConfig.java 에 UserDetailsService 에 설정한 아이디 와 비밀번호 입력 입력합니다.
로그인 후 화면
'백엔드 > Spring Boot 이론' 카테고리의 다른 글
스프링 부트 애플리케이션 테스트 작성 가이드 (1) | 2023.12.07 |
---|---|
스프링부트에서의 OAuth 및 토큰 기반 인증 방식 소개 (1) | 2023.12.06 |
스프링 부트 시큐리티를 사용한 보안 구현 예제 (1) | 2023.12.05 |
스프링 부트에서의 보안과 인증 (1) | 2023.12.05 |
스프링 부트로 RESTful 웹 서비스 구축하기 (1) | 2023.12.04 |