6 Commits

Author SHA1 Message Date
hou27
b54514acab Fix code a bit 2022-06-09 19:00:28 +09:00
hou27
06a5352fb9 Remove old code 2022-06-02 22:38:50 +09:00
hou27
e28750154e Apply Security 5.7.1 2022-06-02 22:00:10 +09:00
hou27
32aa9caf5d Delete useless dto 2022-05-29 04:54:22 +09:00
hou27
9037916237 Change type from User to UserDetails 2022-05-29 04:50:17 +09:00
hou27
9a7ea77820 Implement login with session 2022-05-29 03:02:29 +09:00
14 changed files with 291 additions and 36 deletions

View File

@@ -25,15 +25,20 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
/*
thymeleaf
*/
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
/*
Data JPA
*/
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
/*
Lombok
*/
compileOnly 'org.projectlombok:lombok'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
/*
@@ -44,7 +49,8 @@ dependencies {
/*
Security
*/
implementation 'org.springframework.boot:spring-boot-starter-security'
// implementation 'org.springframework.boot:spring-boot-starter-security:2.6.7'
implementation 'org.springframework.boot:spring-boot-starter-security:2.7.0'
/*
Validation

View File

@@ -1,47 +1,46 @@
package demo.api.config;
import demo.api.user.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
/**
* Spring Security 사용을 위한 Configuration Class를 작성하기 위해서
* WebSecurityConfigurerAdapter를 상속하여 클래스를 생성하고
* @Configuration 애노테이션 대신 @EnableWebSecurity 애노테이션을 추가한다.
*/
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* PasswordEncoder를 Bean으로 등록
*/
@RequiredArgsConstructor
public class SecurityConfig {
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
public UserDetailsService userDetailsService() {
return new UserDetailsServiceImpl();
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
// /**
// * 인증 or 인가가 필요 없는 경로를 설정
// */
// @Override
// public void configure(WebSecurity web) throws Exception {
// web.ignoring().antMatchers("/?/**");
// }
/**
* 인증 or 인가에 대한 설정
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.formLogin().disable()//loginPage("/user/signIn")
.formLogin()
.loginPage("/user/signIn")
.loginProcessingUrl("/user/signInProc")
.usernameParameter("email")
.passwordParameter("password")
.defaultSuccessUrl("/")
.failureUrl("/user/signIn?fail=true");
http
.authorizeRequests()
.antMatchers("/", "/user/signUp").permitAll()
.antMatchers("/", "/user/signUp", "/user/userList", "/user/signIn*").permitAll()
.anyRequest().authenticated();
return http.build();
}
}

View File

@@ -0,0 +1,36 @@
package demo.api.config;
import demo.api.user.domain.User;
import demo.api.user.exception.UserNotFoundException;
import demo.api.user.repository.UserRepository;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String email) throws UserNotFoundException {
User user = userRepository.findByEmail(email)
.orElseThrow(UserNotFoundException::new);
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
return new org
.springframework
.security
.core
.userdetails
.User(user.getEmail(), user.getPassword(), grantedAuthorities);
}
}

View File

@@ -0,0 +1,12 @@
package demo.api.home;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HomeController {
@GetMapping("/")
public String home() {
return "home";
}
}

View File

@@ -2,24 +2,70 @@ package demo.api.user;
import demo.api.user.domain.User;
import demo.api.user.dtos.UserSignUpRequest;
import demo.api.user.exception.UserNotFoundException;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestParam;
/**
* User 관련 HTTP 요청 처리
*/
@RestController
@Controller
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {
private final UserService userService;
@GetMapping("/signUp")
public String signUp() {
return "user/signUp";
}
@PostMapping("/signUp")
public User signUp(@Validated UserSignUpRequest signUpReq) throws Exception {
return userService.signUp(signUpReq);
public String signUp(@Validated UserSignUpRequest signUpReq) throws Exception {
User user = userService.signUp(signUpReq);
return "redirect:/user/signIn";
}
@GetMapping("/signIn")
public String signIn(@RequestParam(value = "fail", required = false) String flag, Model model) {
model.addAttribute("failed", flag != null);
return "user/signIn";
}
// @Autowired
// private UserDetailsService userDetailsService;
@GetMapping("/profile")
public String profile(Model model, @AuthenticationPrincipal UserDetails userDetails) {
// Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
// System.out.println("principal : " + authentication.getPrincipal());
// System.out.println("Implementing class of UserDetails: " + authentication.getPrincipal().getClass());
// System.out.println("Implementing class of UserDetailsService: " + userDetailsService.getClass());
if (userDetails != null) {
User userDetail = userService.findByEmail(userDetails.getUsername())
.orElseThrow(() -> new UserNotFoundException());
model.addAttribute("userDetail", userDetail);
}
return "user/profile";
}
@GetMapping("/user/userList")
public String showUserList(Model model) {
List<User> userList = userService.findAll();
model.addAttribute("userList", userList);
return "user/userList";
}
}

View File

@@ -1,8 +1,11 @@
package demo.api.user.domain;
import demo.api.common.domain.CoreEntity;
import demo.api.user.repository.UserRepository;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
@@ -23,11 +26,15 @@ public class User extends CoreEntity {
@Column(length = 10, nullable = false)
private String name;
// @Enumerated(EnumType.STRING)
// private UserRole role;
@Builder
public User(String email, String password, String name) {
public User(String email, String password, String name /*UserRole role*/) {
this.email = email;
this.password = password;
this.name = name;
// this.role = role;
}
// https://reflectoring.io/spring-security-password-handling/

View File

@@ -0,0 +1,8 @@
package demo.api.user.domain;
import lombok.Getter;
@Getter
public enum UserRole {
ROLE_USER // Spring Security의 role 네이밍 규칙 : ROLE_권한이름
}

View File

@@ -0,0 +1,8 @@
package demo.api.user.exception;
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException() {
super("Can't find User");
}
}

View File

@@ -0,0 +1,17 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div class="container">
<div>
<h1>Test Page</h1>
<p>User</p>
<p>
<a href="/user/signUp">Sign Up</a>
<a href="/user/signIn">Sign In</a>
<br>
<a href="/user/profile">Profile</a>
</p>
</div>
</div>
</body>
</html>

View File

@@ -0,0 +1,24 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div class="container">
<div>
<table>
<thead>
<tr>
<th>#</th>
<th>My Profile</th>
</tr>
</thead>
<tbody>
<tr th:if="${userDetail}">
<td th:text="${userDetail.getEmail()}"></td>
<td th:text="${userDetail.getName()}"></td>
</tr>
</tbody>
</table>
</div>
<a href="/">Home</a>
</div>
</body>
</html>

View File

@@ -0,0 +1,26 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<div class="container">
<div>
<h2>로그인</h2>
</div>
<h3 th:if="${failed}">Fail to login</h3>
<form action="/user/signInProc" method="post">
<div class="form-group">
<label for="email">Email</label>
<input type="email" id="email" name="email" placeholder="Enter your email">
<br/>
<label for="password">PW</label>
<input type="password" id="password" name="password" placeholder="Enter your password">
</div>
<button type="submit">Sign In</button>
</form>
</div>
<a href="/">Home</a>
</body>
</html>

View File

@@ -0,0 +1,24 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div class="container">
<div>
<h2>회원가입</h2>
</div>
<form action="/user/signUp" method="post">
<div class="form-group">
<label for="email">Email</label>
<input type="text" id="email" name="email" placeholder="Enter your email">
<br/>
<label for="password">PW</label>
<input type="text" id="password" name="password" placeholder="Enter your password">
<br/>
<label for="name">Name</label>
<input type="text" id="name" name="name" placeholder="Enter your name">
</div>
<button type="submit">Sign Up</button>
</form>
</div>
<a href="/">Home</a>
</body>
</html>

View File

@@ -0,0 +1,24 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div class="container">
<div>
<table>
<thead>
<tr>
<th>#</th>
<th>User List</th>
</tr>
</thead>
<tbody>
<tr th:each="user : ${userList}">
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
</tr>
</tbody>
</table>
</div>
<a href="/">Home</a>
</div>
</body>
</html>

View File

@@ -18,6 +18,9 @@ import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
@@ -69,6 +72,21 @@ class UserServiceTest {
assertThat(newUser.getPassword()).isNotEqualTo(PASSWORD);
}
@Test
@DisplayName("유저 로그인")
void signIn() throws Exception {
// given
UserSignUpRequest user = createSignUpRequest();
System.out.println("user = " + user.toString());
User newUser = userService.signUp(user);
// when
Boolean flag = newUser.checkPassword(PASSWORD, bCryptPasswordEncoder);
System.out.println("flag = " + flag);
// then
}
@Test
@DisplayName("모든 유저 리스트를 반환")
void findAll() throws Exception {