# 권한 부여 방식
- 권한 부여 방식은 크게 세 가지가 있다.
- MVC 선택기 : 경로에 MVC 식을 이용해 엔드포인트를 선택한다.
- 앤트 선택기 : 경로에 엔트 식을 이용해 엔드포인트를 선택한다.
- 정규식 선택기 : 경로에 정규식을 이용해 엔드포인트를 선택한다.
# 선택기 메서드 활용
- 선택기 메서드를 통해 권한을 부여하는 방식은 아래와 같다.
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic() ;
http.authorizeRequests()
.mvcMatchers("/hello/**").hasRole("ADMIN")
.mvcMatchers("/ciao/**").hasRole("MANAGER") ;
}
- 그 외의 Api 관련 권한 설정은 아래와 같이 해준다.
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic() ;
http.authorizeRequests()
.mvcMatchers("/hello/**").hasRole("ADMIN")
.mvcMatchers("/ciao/**").hasRole("MANAGER")
// 위의 명시된 Api 외의 다른 모든 Api는 모두 접근 허용
.anyRequest().permitAll() ;
// 위의 명시된 Api 외의 다른 모든 Api는 인증된 사용자만 접근 허용
.anyRequest().authenticated() ;
}
#MVC 선택기로 권한 부여 설정
- mvcMatchers(HttpMethod method, String... patterns) : 같은 경로에 대해 Http 방식별로 다른 제한을 적용할 때 유용하다.
- mvcMatchers(String... patterns) : 경로만을 기준으로 권한 부여 제한을 적용할 때 더 쉽게 이용할 수 있다.
- 아래의 코드와 같이 HttpMethod에 경로를 설정하여 authenticated() 또는 permitAll과 같은 권한을 부여할 수 있다.
@Override
public void configure(HttpSecurity http) throws Exception {
http.httpBasic() ;
http.authorizeRequests()
.mvcMatchers(HttpMethod.GET, "/a")
.authenticated()
.mvcMatchers(HttpMethod.POST, "/a")
.permitAll()
.anyRequest()
.denyAll() ;
http.csrf().disable() ;
}
- PathVariable에 특정 정규식을 적용하고 싶은 경우 아래와 같이 설정해주면 된다.
- code값은 0~9의 숫자만 입력할 수 있으며, 문자 입력시에는 403 Forbidden 에러가 발생한다.
@Override
public void configure(HttpSecurity http) throws Exception {
http.httpBasic() ;
http.authorizeRequests()
.mvcMatchers("/product/{code:^[0-9]*$}")
.permitAll()
.anyRequest()
.denyAll() ;
}
# 앤트 선택기로 권한을 부여할 요청 선택
- 엔드포인트의 경로를 직접 설정하여 권한을 부여할 수 있다.
- "/hello"와 "/hello/" 모두 동작하는 결함이 있기 때문에 실제로 잘 사용되진 않지만, 레거시 시스템 중에는 사용하는 경우도 있다.
@Override
public void configure(HttpSecurity http) throws Exception {
http.httpBasic() ;
http.authorizeRequests()
.mvcMatchers("/hello")
.authenticated() ;
}
# 정규식 선택기로 권한을 부여
- 경로에 특정 기호나 문자가 있으면 모든 요청을 거부하는 경우에 활용할 수 있다.
- 읽기 어렵다는 단점이 존재한다.
- regexMatchers(HttpMethod method, String regex) : HTTP 방식별로 다른 제한을 적용할 때 유용하다.
- regexMatchers(String regex) : 경로만을 기준으로 권한 부여 제한을 적용하는 경우에 유용하다.
- 아래의 코드 예시 참조
@Override
public void configure(HttpSecurity http) throws Exception {
http.httpBasic() ;
http.authorizeRequests()
.regexMatchers(".*/(us|uk|ca)+/(en|fr).*")
.authenticated()
.anyRequest()
.hasAuthority("premium") ;
}
@GetMapping("/video/{country}/{language}")
public String video(@PathVariable String country,
@PathVariable String language) {
return "Video allowed for " + country + " " + language ;
}