Digking's cave

My First Blog Project (13) : 비밀번호 해쉬화 회원가입 / 권한에 따른 페이지 처리 본문

Spring/My First Blog Project

My First Blog Project (13) : 비밀번호 해쉬화 회원가입 / 권한에 따른 페이지 처리

디깅 2022. 12. 20. 14:00
728x90

 

sercive에서 비밀번호 해쉬화 + role 세팅까지 하고

controller에서는 실제 save만 진행하도록 한다.

 

UserApiController.java

package com.cos.blog.controller.api;

import com.cos.blog.dto.ResponseDto;
import com.cos.blog.model.RoleType;
import com.cos.blog.model.User;
import com.cos.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class UserApiController {

    @Autowired
    private UserService userService;

    @PostMapping("/auth/joinProc")
    public ResponseDto<Integer> save(@RequestBody User user) { // username, password, email
        userService.회원가입(user);
        return new ResponseDto<Integer>(HttpStatus.OK.value(), 1);

    }



}

UserService.java

package com.cos.blog.service;

import com.cos.blog.model.RoleType;
import com.cos.blog.model.User;
import com.cos.blog.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private BCryptPasswordEncoder encoder;

    @Transactional
    public void 회원가입(User user){
        String rawPassword = user.getPassword(); //1234 원문 비밀번호
        String encPassword = encoder.encode(rawPassword); //해쉬 비밀번호
        user.setPassword(encPassword);
        user.setRoles(RoleType.USER);
        userRepository.save(user);

    }

}

BCryptPasswordEncoder 

- SpringSecurity 에서 제공하는 클래스

- 비밀번호를 암호화 하는 메서드를 가졌다

  .encode() 로 해쉬비밀번호화 한다.

 

SecurityConfig.java

package com.cos.blog.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration //빈등록 (IoC관리)
@EnableWebSecurity //security 필터 등록
@EnableGlobalMethodSecurity(prePostEnabled = true) //특정 주소를 접근을 하면 권한 및 인증을 미리 체크하겠다는 뜻
public class SecurityConfig {

    @Bean
    public BCryptPasswordEncoder encoderPWD(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .csrf().disable() //csrf 토큰 비활성화(테스트 시에는 걸어두는게 좋다)
                .authorizeRequests()
                   .antMatchers("/","/auth/**","/js/**","/css/**","/image/**")
                     .permitAll()
                    .anyRequest()
                  .authenticated()
                .and()
                    .formLogin()
                    .loginPage("/auth/loginForm");
        return http.build();
    }

}

권한없어도 메인과 js등 로그인에 필요한 화면들 접근 가능하도록 .antMatchers 주소 확장

- 해놓지 않으면, 로그인 버튼 누른 후에 js 등의 화면에 접근을 못함

반응형