BootCamp 54day

GyeongNamΒ·2024λ…„ 2μ›” 6일
0

BootCamp

λͺ©λ‘ 보기
48/49
post-thumbnail

πŸ“… 2024λ…„ 01μ›” 30일


54일차 : Spring (14)

Spring Security & Session Login

  • SecurityConfig
/*
websecurityconfigureradapter을 μƒμ†ν•˜λŠ” 방식은 μ§€μ›μ’…λ£Œλ˜μ—ˆλ‹€.
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // pre : 사전 , post : 사후, 사전.사후에 인증/κΆŒν•œ 검사 μ–΄λ…Έν…Œμ΄μ…˜ μ‚¬μš© κ°€λŠ₯
public class SecurityConfig {
    @Bean
    public SecurityFilterChain myFilter(HttpSecurity httpSecurity) throws  Exception {
        return httpSecurity
                .csrf().disable()   // csrf λ³΄μ•ˆ 곡격에 λŒ€ν•œ 섀정은 ν•˜μ§€ μ•Šκ² λ‹€.
                .authorizeRequests()    // νŠΉμ • url λŒ€ν•΄μ„œλŠ” λ³΄μ•ˆμ„ μΈμ¦μ²˜λ¦¬ν•˜μ§€ μ•Šκ³ , νŠΉμ • url λŒ€ν•΄μ„œλŠ” 인증처리 ν•˜κ² λ‹€λŠ” μ„€μ •
                    .antMatchers(
                            "/",
                            "/author/create",
                            "/author/login-page"
                    )  // μΈμ¦ν•„μš”μ—†λŠ” νŽ˜μ΄μ§€
                    .permitAll()
                    .anyRequest().authenticated() // κ·Έ μ™ΈλŠ” λͺ¨λ‘ 인증 ν•„μš”
                .and()  // λ§Œμ•½μ— μ„Έμ…˜μ„ μ‚¬μš©ν•˜μ§€ μ•ŠμœΌλ©΄ μ•„λ‚΄ λ‚΄μš©μ„ μ„€μ •
//                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .formLogin()
                    .loginPage("/author/login-page")        // 둜그인 νŽ˜μ΄μ§€ μ„€μ •
                    // μŠ€ν”„λ§ λ‚΄μž₯ λ©”μ„œλ“œλ₯Ό μ‚¬μš©ν•˜κΈ° μœ„ν•΄ /doLogin url μ‚¬μš©
                    .loginProcessingUrl("/doLogin")
                        .usernameParameter("email")
                        .passwordParameter("pw")
                .successHandler(new LoginSuccessHandler())
                .and()
                .logout()
                    // μŠ€ν”„λ§ λ‚΄μž₯ λ©”μ„œλ“œλ₯Ό μ‚¬μš©ν•˜κΈ° μœ„ν•΄ /doLogout url μ‚¬μš©
                    .logoutUrl("/doLogout")
                .and()
                .build();
    }
}
  • LoginService
@Slf4j
@Service
public class LoginService implements UserDetailsService {
    private final AuthorService authorService;
    @Autowired
    public LoginService(AuthorService authorService) {
        this.authorService = authorService;
    }
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Author author = authorService.findByEmail(username);
        List<GrantedAuthority> authorities = new ArrayList<>();
        // ROLE_ κΆŒν•œ νŒ¨ν„΄μœΌλ‘œ μŠ€ν”„λ§μ—μ„œ 기본적으둜 κΆŒν•œ 체크
        authorities.add(new SimpleGrantedAuthority(
               "ROLE_" + author.getRole().toString()
        ));
        /*
        λ§€κ°œλ³€μˆ˜ : userEmail, userPassword, authorities
        ν•΄λ‹Ή λ©”μ„œλ“œμ—μ„œ return λ˜λŠ” User κ°μ²΄λŠ” session λ©”λͺ¨λ¦¬ μ €μž₯μ†Œμ— μ €μž₯λ˜μ–΄ 계속 μ‚¬μš© κ°€λŠ₯
         */
        return new User(author.getEmail(), author.getPassword(), authorities);
    }
}
  • LoginSuccessHandler
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        HttpSession httpSession = request.getSession();
        httpSession.setAttribute("email", authentication.getName());
        response.sendRedirect("/");
    }
}
  • RedisConfig
@Configuration
public class RedisConfig {
    //    Value : yml에 μžˆλŠ” 정보λ₯Ό ν”„λ‘œκ·Έλž¨μ•ˆμœΌλ‘œ κ°€μ Έμ˜€λŠ” μ–΄λ…Έν…Œμ΄μ…˜
    @Value("${spring.redis.host}")
    public String host;
    @Value("${spring.redis.port}")
    private int port;
    @Bean
    public RedisConnectionFactory redisConnectionFactory(){
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setHostName(host);
        redisStandaloneConfiguration.setPort(port);
        return new LettuceConnectionFactory(redisStandaloneConfiguration);
    }
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }
}

λ‚˜μ€‘μ— λ‹€μ‹œ 정리할 것!


Spring μ‹€μŠ΅ github 링크

profile
503 Service Unavailable Error

0개의 λŒ“κΈ€