2023 여름 모각코 - 절개와지조

[모각코 / 230716] spring security를 이용해 회원가입 구현하기

2023. 8. 17. 21:58
반응형

 

안녕하세요 모각코 4일차입니다. 

 

 

오늘은 spring security를 사용하며 securityConfig 파일을 만들어서 각 페이지 별로 권한을 넣어주었습니다. 

그리고 user 모델을 생성하고 jpa repository를 사용하여 회원가입을 구현해보았습니다. (service는 따로 구현하지 않고 바로 jpa repository를 사용함) 

 

 

 

IndexController.java

로우팅은 이렇게 했습니다. 

@GetMapping("/user")
public @ResponseBody String user() {
    return "user";
}

@GetMapping("/admin")
public @ResponseBody String admin() {
    return "admin";
}

@GetMapping("/manager")
public @ResponseBody String manager() {
    return "manager";
}

// 스프링 시큐리티 해당주소를 낚아챔 -> springConfig 파일 생성 후 작동 안 함
@GetMapping("/loginForm")
public @ResponseBody String login() {
    return "loginForm";
}

@PostMapping("/login")
public String login() {
    return "";
}

@GetMapping("/joinForm")
public String joinForm() {
    return "joinForm";
}

@PostMapping("/join")
public String join(UserRequestDto userRequestDto) {

    // 패스워드 암호화를 하지 않으면 security 를 사용할 수 없음
    String rawPassword = userRequestDto.getPassword();
    // bCryptPasswordEncoder를 이용하여 db 저장 시 encoding 됨
    String encPassword = bCryptPasswordEncoder.encode(rawPassword); 

    userRepository.save(User.builder()
            .username(userRequestDto.getUsername())
            .password(encPassword)
            .email(userRequestDto.getEmail())
            .role("ROLE_USER")
            .build());
    return "redirect:/loginForm";
}

 

 

SecurityConfig.java

WebSecurityConfigurerAdapter를 이용하여 configure을 적용했습니다. 

 

/user 로 접근하면 authenticated 즉 인증이 필요하다는 뜻입니다. 

/manager와 /admin으로 접근 시에는 authorization 즉 admin인지 manager인지 인증이 필요하다는 뜻입니다.

그 외의 주소는 모두 허용하며 인증이 필요할 경우 바로 login 페이지로 이동하게 설정했습니다. 

@Configuration
@EnableWebSecurity // 스프링 시큐리티 필터가 스프링 필터체인에 등록
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests()
                .antMatchers("/user/**").authenticated()
                .antMatchers("/manager/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_MANAGER')")
                .antMatchers("/admin/*").access("hasRole('ROLE_ADMIN')")
                .anyRequest().permitAll() // 위의 세 가지 주소가 아니라면 모두 허용한다
                .and()
                .formLogin()
                .loginPage("/loginForm")
                .loginProcessingUrl("/login") // /login 주소가 호출되면 security 가 낚아서 로그인을 진행함
                .defaultSuccessUrl("/");
    }
}

 

그런데 사실 WebSecurityConfigurerAdapter는 deprecated 되었기 때문에 다른 방법을 사용하여 config를 적용해야합니다. 그것은 바로 SecurityFilterChain을 Bean으로 등록하여 사용하는 방법입니다. 

 

그리고 spring security를 사용하면 password의 encode 작업을 해주어야하기 때문에 config 파일에 BCryptPasswordEncode를 빈으로 생성합니다. 

// WebSecurityConfigurerAdapter 는 deprecated 되어
// SecurityFilerChain 을 Bean 으로 등록하여 사용

@Configuration
@EnableWebSecurity // 스프링 시큐리티 필터가 스프링 필터체인에 등록
public class SecurityConfig {

    @Bean // 해당 메서드의 리턴되는 오브젝트를 IoC로 등록
    public BCryptPasswordEncoder encodePwd() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests()
                .antMatchers("/user/**").authenticated()
                .antMatchers("/manager/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_MANAGER')")
                .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
                .anyRequest().permitAll()
                .and()
                .formLogin()
                .loginPage("/loginForm")
                .loginProcessingUrl("/login") // /login 주소가 호출되면 security 가 낚아서 로그인을 진행함
                .defaultSuccessUrl("/");
        return http.build();
    }
}

 

 

joinForm.html

<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="UTF-8">
        <title>회원가입 페이지</title>
    </head>
    <body>
      <h1>회원가입 페이지</h1>
      <hr>
      <form action="/join" method="post">
        <input type="text" name="username" placeholder="Username"><br/>
        <input type="password" name="password" placeholder="Password"><br/>
        <input type="email" name="email" placeholder="Email"><br/>
        <button type="submit">회원가입</button>
      </form>
    </body>
</html>

 

 

loginForm.html

<!doctype html>
<html lang="ko">
    <head>
        <meta charset="UTF-8">
        <title>로그인 페이지</title>
    </head>
    <body>
        <h1>로그인 페이지</h1>
        <hr>
        <form>
            <input type="text" name="username" placeholder="Username"><br>
            <input type="password" name="password" placeholder="Password"><br>
            <button type="submit">로그인</button>
        </form>
        <a href="/joinForm">회원가입</a>
    </body>
</html>

 

 

 

User.java

db에 접근하는 부분이기 때문에 data와 같은 어노테이션을 사용하지 않았기 때문에 User에서 Controller에서 form으로 부터 값을 받을 때 바로 받을 수 없었습니다. 

@Entity
@Builder
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String username;
    private String password;
    private String email;
    private String role; // ROLE_USER, ROLE_ADMIN
    @CreationTimestamp
    private Timestamp createDate;

}

 

그래서 UserRequestDto를 생성하여 구현했습니다. 

UserRequestDto.java

@Data
public class UserRequestDto {
    private String username;
    private String password;
    private String email;
}

 

회원가입 이후에 db에 저장된 결과입니다. 

비밀번호는 encoding 되어 있는 것을 확인할 수 있습니다. 

 

 

 

 

메타코딩님의 강의를 보며 제 방식대로 바꾸어 공부했습니다. 

 

https://youtu.be/aOYqLaQLb4o

 

반응형
저작자표시 (새창열림)

'2023 여름 모각코 - 절개와지조' 카테고리의 다른 글

[모각코 / 230822] spring security OAuth 로그인 구현하기  (0) 2023.08.19
[모각코 / 230720] spring security 를 이용해 로그인 구현하기 (@EnableGlobalMethodSecurity)  (0) 2023.08.17
[모각코 / 230713] spring security 기본적인 환경 설정  (0) 2023.08.13
[모각코 / 230708] 객체지향의 사실과 오해 - 이상한 나라의 객체  (0) 2023.07.11
[모각코 / 230706] 객체지향의 사실과 오해 - 협력하는 객체들의 공동체  (0) 2023.07.11
'2023 여름 모각코 - 절개와지조' 카테고리의 다른 글
  • [모각코 / 230822] spring security OAuth 로그인 구현하기
  • [모각코 / 230720] spring security 를 이용해 로그인 구현하기 (@EnableGlobalMethodSecurity)
  • [모각코 / 230713] spring security 기본적인 환경 설정
  • [모각코 / 230708] 객체지향의 사실과 오해 - 이상한 나라의 객체
pkyung
pkyung
성장하는 중pkyung 님의 블로그입니다.
pkyung
성장하는 중
pkyung
전체
오늘
어제
  • 분류 전체보기
    • 🏆토이 프로젝트에서 생긴 일
    • 🤿백엔드 내실 채우기
    • 🍫카카오 테크 캠퍼스 2기 BE
    • 🍀spring
      • 스프링 입문
      • 스프링 핵심원리 기본
      • 스프링 jpa
      • 🐛debug
    • 🔒보안
    • 🌎infra
      • docker
      • kubernetes
      • cloud
    • 🌐web
      • HTTP 웹 기본 지식
    • 🔑알고리즘
      • baekjoon
      • programming language
    • 🎞️프로젝트
      • android
      • flutter
    • 📚수업
      • 교양과목
    • 💾database
    • ⚙settings
    • 2023 여름 모각코 - 절개와지조
    • 2024 겨울 모각코 - 내 장점은 algorit..

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • HTTP
  • python
  • 백준
  • 데이터베이스
  • BFS
  • be
  • Security
  • spring
  • 코드리뷰
  • 스프링부트
  • 스프링기본
  • 카테캠
  • Docker
  • 파이썬
  • 소수
  • mysql
  • 자바
  • JPA
  • 김영한
  • 스택
  • sql
  • 문자열
  • nginx
  • 객체지향
  • 스프링
  • 객체지향의사실과오해
  • Java
  • springboot
  • 카카오테크캠퍼스
  • 자바문자열

최근 댓글

최근 글

hELLO · Designed By 정상우.
pkyung
[모각코 / 230716] spring security를 이용해 회원가입 구현하기
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.