Spring Security :: Config 파일 설정

hyunjoon park·2023년 11월 23일
1

Spring Security

목록 보기
1/12
post-thumbnail

Spring Boot에 대해서 알아보자

Spring Security는 기본적으로 사용을하게 되면 모든 페이지에 대해서 로그인을 하도록 되어있다.
우리는 Config 클래스 파일을 통해서 이 설정을 직접 지정해줄 수 있다.

--- SecurityConfig ---

package bsm.choi.fancafe.global.config;

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;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(
                        (auth) -> auth.requestMatchers("/").permitAll()
                );

        return http.build();
    }
}

@Configuration 을 사용하여 Config 파일로 설정해주고
@EnableWebSecurity 를 사용하여 WebSecurity를 활성화 시켜준다

SecurityFilterChain 인터페이스 형으로 메소드를 생성해주고 예외처리를 위한 throws Exception을 해주자.

http를 build() 하여 리턴시켜주면 된다.


경로 접속 권한

http.authorizeHttpRequests 메소드를 통하여 특정 경로로 요청왔을 때 어떤 사용자한테 오픈하여 줄지 정할 수 있다.

작성방법 : 람다방식 () ->

(auth) -> auth.requestMatchers("/")

requestMatchers 메소드 안에 경로를 적으면 그 경로에 대해서 권한을 준다는 뜻이고

이제 권한을 나타내는 방법을 알아보자


.permitAll() : 모든 사용자에게 로그인 하지 않아도 접근 할 수 있도록 설정
.hasRole() : 특정한 role이 있어야 로그인을 한 뒤에 특정한 규칙이 있어야 경로로 접근 가능
.authenticated() : 로그인만 진행하면 모두 접근 가능
.denyAll() : 모든 사용자가 로그인을 진행해도 접근 못함


package bsm.choi.fancafe.global.config;

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;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
        	.authorizeHttpRequests(
            	(auth) -> auth
                	.requestMatchers("/", "/login", "/admin/login").permitAll()
                    .requestMatchers("/admin").hasRole("ADMIN")
                    .anyRequest().permitAll()
            );

        return http.build();
    }
}

.requestMatchers("/admin").hasRole("ADMIN")는 /admin 이라는 경로에 "ADMIN" 이라는 role을 가진 사용자만 접속할 수 있다는 것이고

.anyRequest().permitAll 는 위에 지정되지 않은 다른 모든 경로에 대해서 모든 사용자의 접속을 허용한다는 뜻이다.

위에서 부터 실행이 되기 때문에 위에서 모든 경로를 지정해주면 밑의 설정이 먹히지 않음 주의!!!


서버를 열고 경로로 접속하면 엑세스 권한 거부됨이라는 화면이 뜨는 이유는
특정한 경로, 경로에 대한 권한을 설정해 주었는데 로그인도 되어있지 않고, role도 지정이 안되어있기 때문이다

SecurityConfig 파일을 작성하면 loginForm을 작성해야한다

다음 블로그에서 작성해보겠다

profile
Backend Developer

0개의 댓글