1. Entity 만들기
package com.example.my.module.user.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserEntity {
private Integer idx;
private String id;
private String pw;
private Character deleteYn;
private LocalDateTime createDate;
private LocalDateTime updateDate;
private LocalDateTime deleteDate;
}
package com.example.my.module.user.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserRoleEntity {
private Integer idx;
private Integer userIdx;
private String role;
private LocalDateTime createDate;
}
2. Repository 만들기
package com.example.my.module.user.repository;
import com.example.my.module.todo.entity.TodoEntity;
import com.example.my.module.user.entity.UserEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
@Mapper
public interface UserRepository {
UserEntity findById(String id);
List<TodoEntity> findByIdAndDeleteYn(@Param("id") String id, @Param("deleteYn") Character deleteYn);
Integer insert(UserEntity userEntity);
}
package com.example.my.module.user.repository;
import com.example.my.module.user.entity.UserRoleEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
@Repository
@Mapper
public interface UserRoleRepository {
UserRoleEntity findByUserIdx(Integer userIdx);
UserRoleEntity findByUserIdxAndRole(@Param("userIdx") Integer userIdx, @Param("role") String role);
UserRoleEntity findRoleByUserIdx(Integer userIdx);
Integer insert(UserRoleEntity userRoleEntity);
}
- UserRepository.java
- 여기서 매개변수를 두개 받을려면 @Param을 사용
3. Controller 만들기
package com.example.my.module.user.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/auth")
public class AuthController {
@GetMapping("/join")
public String getJoinPage(){
return "join";
}
@GetMapping("/login")
public String getLoginPage(){
return "login";
}
}
package com.example.my.module.user.controller;
import com.example.my.module.user.dto.AuthDTO;
import com.example.my.module.user.service.AuthServiceApiV1;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1/auth")
public class AuthControllerApiV1 {
private final AuthServiceApiV1 authServiceApiV1;
@PostMapping("/join")
public HttpEntity<?> joinProc(@Validated @RequestBody AuthDTO.ReqJoin reqDto){
return authServiceApiV1.joinProc(reqDto);
}
}
package com.example.my.module.user.controller;
public class UserController {
}
4. Dto 만들기
package com.example.my.module.user.dto;
import com.example.my.module.user.entity.UserEntity;
import lombok.*;
import org.springframework.security.crypto.password.PasswordEncoder;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.time.LocalDateTime;
public class AuthDTO {
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class ReqJoin{
@NotBlank(message = "아이디를 입력하세요.")
@Size(min = 3, message = "아이디는 3자 이상 입력해주세요.")
private String id;
@NotBlank(message = "비밀번호를 입력하세요.")
@Size(min = 3, message = "비밀번호는 3자 이상으로 입력해주세요.")
private String pw;
public UserEntity toEntity(PasswordEncoder passwordEncoder){
return UserEntity.builder()
.id(id)
.pw(passwordEncoder.encode(pw))
.deleteYn('N')
.createDate(LocalDateTime.now())
.build();
}
}
}
5. Service 만들기
package com.example.my.common.security;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf().disable();
// h2를 볼려고
httpSecurity.authorizeHttpRequests(config -> {
try {
config
.antMatchers("/h2/**")
.permitAll()
.and()
.headers().frameOptions().sameOrigin();
} catch (Exception e) {
throw new RuntimeException(e);
}
});
// 시큐리티 기본 상태 - 인가 Authorization(인증 Authentication + 권한 Authority)
httpSecurity.authorizeHttpRequests(config -> config
// 패턴에 해당하는 주소는 허용
.antMatchers("/auth/login","/auth/join","/api/*/auth/**")
.permitAll()
// 모든 페이지를 인증하게 만듬
.anyRequest()
.authenticated());
// formLogin과 관련된 내용
httpSecurity.formLogin(config -> config
.loginPage("/auth/login")
.loginProcessingUrl("/login-process")
.usernameParameter("id")
.passwordParameter("pw")
// 로그인 성공 시 이동 페이지
// 두번째 매개변수는 로그인 성공 시 항상 세팅 페이지로 이동하게 함
.defaultSuccessUrl("/todoList", true));
return httpSecurity.build();
}
}