찌니의 프로그래밍 삼매경

[Spring Boot] spring security 기록용2 (회원수정 관련) 본문

Spring

[Spring Boot] spring security 기록용2 (회원수정 관련)

zzI니☆ 2021. 2. 12. 17:00
728x90

 

회원수정

DB, 세션 둘다 수정되는 로직 

기록한다

필요한 내용 주석으로 달아둠

OAUTH2 작업중으로 수정예정

 

1. UserApiContoller

    @PutMapping("/user")
    public ResponseDto<Integer> update(@RequestBody User user){
        userService.update(user);
        // 여기서는 트랜잭션이 종료되기 때문에 DB값은 변경이 됐음
        // 하지만 세션값은 변경되지 않은 상태이기때문에 세션값 갱신이 필요함

        // 세션 등록
        Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));
        SecurityContextHolder.getContext().setAuthentication(authentication);

        return new ResponseDto<Integer>(HttpStatus.OK.value(), 1);
    }

 

2. UserService

    @Transactional
    public void update(User user){
        // 수정시에는 영속성 컨텍스트 User 오브젝트를 영속화시키고 영속화된 User 오브젝트를 수정
        // SELECT를 해서 User오브젝트를 DB로부터 가져오는 이유는 영속화를 하기위함
        // 영속화된 오브젝트를 변경하면 자동으로 DB에 update를 날려주기때문
        User persistance = userRepository.findById(user.getId()).orElseThrow(()->{
            return new IllegalArgumentException("회원 찾기 실패!!");
        });
        String rawPassword = user.getPassword();
        String encPassword = bCryptPasswordEncoder.encode(rawPassword);
        persistance.setPassword(encPassword);
        persistance.setEmail(user.getEmail());

        // 회원수정 함수 종료시 서비스종료 = 트랜잭션 종료 = commit 이 자동으로 실행
        // 영속화된 persistance 객체의 변화가 감지되면 더티체킹이 되어 update문을 날려줌
    }

3. SecurityConfig

새로 등록한

 

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

 

이 부분이 회원수정 시 세션변경 할때 필요하다

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private PrincipalDetailService principalDetailService;

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

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    // 시큐리티가 대신 로그인해주는데 password를 가로채기 하기에
    // 해당 password가 뭘로 해쉬가 되어 회원가입이 되었는지 알아야
    // 같은 해쉬로 암호화하여 DB에 있는 해쉬랑 비교 가능
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(principalDetailService).passwordEncoder(bCryptPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()   // csrf 토큰 비활성화
            .authorizeRequests()
                .antMatchers("/","/auth/**", "/js/**", "/css/**", "/image/**", "/dummy/**")
                .permitAll()
                .anyRequest()
                .authenticated()
            .and()
                .formLogin()
                .loginPage("/auth/loginForm")
                .loginProcessingUrl("/auth/loginProc") // 스프링 시큐리티가 해당 주소로 요청오는 로그인을 가로챈다.
                .defaultSuccessUrl("/");
        ;
    }
}
728x90
Comments