본문 바로가기
개발/Security

[SpringBoot] Security 로그인 인증, 인가(2) - SecurityConfig

by 코딩하는 흰둥이 2023. 4. 30.
반응형

이전글 https://greed-yb.tistory.com/223

 

[SpringBoot] Security 로그인 인증, 인가(1) - 환경설정

Java 17 Maven Spring Boot 3.0.3 Spring Security 3.0.4 Oracle 11g Mybatis IntelliJ Ultimate DBeaver Thymeleaf 폴더 구조 더보기 Security 한번 구현해보겠다고 일주일 내내 작업한거 같다 거의 대부분의 예제들은 3.0.0 이하의

greed-yb.tistory.com

 

 

SecurityConfig
package com.example.practice.security.config;


import com.example.practice.security.handler.WebAccessDeniedHandler;
import com.example.practice.security.handler.WebAuthenticationEntryPoint;
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.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

// @EnableWebSecurity는 모든 요청 URL이 스프링 시큐리티의 제어를 받도록 만드는 애너테이션이다.
// @Configuration은 스프링의 환경설정 파일임을 의미하는 애너테이션이다. 여기서는 스프링 시큐리티의 설정을 위해 사용되었다. 

@EnableWebSecurity
@Configuration
public class WebSecurityConfig {
    
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        // @EnableWebSecurity 이 csrf 공격을 방지하기 때문에 해당 기능을 disable로 변경
		http.csrf().disable(); 
        
        http
                .authorizeRequests()
                // 권한체크 - 내부적으로 ROLE_ 을 붙이기 때문에 ROLE_ 뒷부분만 적어준다 (USER 권한)
                .requestMatchers("/").hasRole("USER")      
                // 권한체크 - 내부적으로 ROLE_ 을 붙이기 때문에 ROLE_ 뒷부분만 적어준다 (ADMIN 권한)
                .requestMatchers("/board/create").hasAnyRole("ADMIN")
                // 해당 경로는 권한이 없어도 접속할 수 있다
                .requestMatchers("/bootstrap/**", "/login", "/signup", "/logout").permitAll()
                .anyRequest().authenticated();

        // 로그인(설정하지 않으면 기본 login page를 사용하게 됨
        http
                .formLogin()
                .loginPage("/login")             // 로그인 페이지 지정 지정
                .loginProcessingUrl("/login")    // 로그인 처리 URL 지정
                .usernameParameter("id")         // form의 id 변수 명
                .passwordParameter("password")   // form의 패스워드 변수 명
                .defaultSuccessUrl("/");         // 로그인 성공시 이동할 주소

        // 로그아웃
        http
                .logout()
                .logoutUrl("/logout")           // 로그아웃 url
                .logoutSuccessUrl("/")          // 로그아웃 성공시 /로 이동
                .invalidateHttpSession(true);   // 인증정보 삭제 세션 무효화

        // exception 처리
        http
                .exceptionHandling()
                // 인가 권한이 없는 사용자 접근 시
                .accessDeniedHandler(new WebAccessDeniedHandler())               
                // 인증되지 않은 사용자 접근 시
                .authenticationEntryPoint(new WebAuthenticationEntryPoint());      

        return http.build();
    }

}

 

댓글