[Spring Security] Authorization

수깡·2024년 2월 26일

Spring Security

목록 보기
3/11

🌟Authorities

권한을 결정할 때, AccessDecisionManagerGrantedAuthority를 읽어 결정한다. GrantedAuthority는 메소드가 하나 뿐인 인터페이스로, getAuthority()를 메소드로 가진다. 이메소드로 명확한 String으로 권한을 조회할 수 있다. String으로 표현할 수 없다면 복잡한 케이스로 간주하고, null을 리턴한다. null을 리턴했다는 것은, AccessDecisionManagerGrantedAuthority를 이해하기 위한 구체적인 코드가 있어야 한다는 뜻이다.
스프링 시큐리티는 GrantedAuthority의 구현체 SimpleGrantedAuthority를 제공하는데, 사용자가 지정한 String을 GrantedAuthority로 변환해준다. 모든 AuthenticationProvider는 이를 사용하여 권한을 부여한다.
기본적으로 권한을 부여할 때 권한은 ROLE_ 접두사로 시작하고, 보안 컨텍스트에 USER 역할을 요구하는 권한 부여 규칙이 있는 경우 getAuthorityROLE_USER를 반환하는 것을 찾는다.
GrantedAuthorityDefaults접두사를 사용자 정의할 수 있다.

🌟 접근 제어 메소드

  • permitAll() : 경로 상 모든 접근 승인
  • denyAll() : 경로 상 모든 접근 거부
  • hasAuthority(String authority) : 매개변수로 주어진 권한만 접근을 승인. "USER"를 넣을 경우 USER 권한을 가진 회원만 접근 승인
  • hasAnyAuthority(String authorities): 매개변수로 주어진 하나 이상의 권한을 접근 승인
  • hasRole : hasAuthority의 단축 메서드로, (역할을 선언 할 때)ROLE_접두사를 사용.
  • hasAnyRole : hasAnyAuthority의 단축 메서드로, 마찬가지로 (역할을 선언할 때)ROLE_접두사를 사용
  • access(String attribute): 사용자 정의 규칙을 구현하여 액세스를 결정. Spring Expression Language(SpEL)을 매개변수로 받아 접근 설정.

🌟 Matcher method

  • requestMatchers
    두가지 방법으로 사용가능하다.
   http.authorizeRequests()
                .requestMatchers("/members").permitAll()
                .anyRequest().denyAll();
                
                http.authorizeRequests()
                .requestMatchers(HttpMethod.GET).permitAll()
                .anyRequest().denyAll();

HttpMethod.GET 매개변수를 붙이지 않아도 GET을 제외한 모든 http method는 crsf 방어 로직으로 인해 접근이 불가능하다. 따라서 다른 메소드로 접근하고 싶다면 http.csrf().disable(); 을 통해 csrf 설정을 끌 수 있다.

*regexMatchers
정규 표현식에 대한 일치 요청도 받을 수 있다.

http
    .authorizeHttpRequests((authorize) -> authorize
        .requestMatchers(RegexRequestMatcher.regexMatcher("/resource/[A-Za-z0-9]+")).hasAuthority("USER")
        .anyRequest().denyAll()
    )

예제

@Configuration
@EnableWebSecurity
public class SecurityConfig {

	@Bean
	public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
		http
			.securityMatcher("/api/**")                            
			.authorizeHttpRequests(authorize -> authorize
				.requestMatchers("/user/**").hasRole("USER")       
				.requestMatchers("/admin/**").hasRole("ADMIN")     
				.anyRequest().authenticated()                      
			)
			.formLogin(withDefaults());
		return http.build();
	}
}

출처: 스프링 시큐리티 공식 문서

0개의 댓글