23/05/09(Spring+TodoList+Login+회원가입까지)

조영문·2023년 5월 9일
0

Spring

목록 보기
6/7
post-thumbnail

Security(시큐리티)

TodoList에 로그인 기능까지 추가

화면

  • 로그인
  • 회원가입
  • TodoList(로그인성공시)
    -> 다음시간에

코드 및 설정

유저까지해서 todoList에서 로그인까지 하기

  • application.yml에 추가
  1. exception에 추가
  2. AuthServiceApiV1에서 예외처리 받기

1. Entity 만들기

  • UserEntity.java
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;

}
  • UserRoleEntity.java
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 만들기

  • UserRepository.java
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);
}
  • UserRoleRepository.java
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 만들기

  • AuthController.java
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";
    }

}
  • AuthControllerApiV1.java
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);
    }
}
  • UserController.java
package com.example.my.module.user.controller;

public class UserController {
}

4. Dto 만들기

  • AuthDTO.java
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 만들기

  • SecurityConfig.java
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();

    }

}
  • h2/schema.sql

0개의 댓글