🗯️ 문제
api 페이지별 접근권한을 설정해야 합니다.
예시코드처럼
WebSecurityConfigurerAdapter
를 상속하는 클래스에서 configure(HttpSecurity http)
메서드를 오버라이드 해서 상세하게 설정 가능합니다.@Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .addFilter(corsFilter) .httpBasic().disable() .formLogin().disable() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() .addFilter(new JwtAuthorizationFilter(authenticationManager(), jwtAuthenticationProvider())) .authorizeRequests() .antMatchers("/api/v1/signup") .anonymous() .antMatchers("/api/v1/logout") .access("hasRole('ROLE_USER') or hasRole('ROLE_BUSINESS')") .antMatchers("/api/v1/login") .anonymous() ... .anyRequest() .permitAll(); }
각 api 주소마다 승인하는 권한정보를 입력해줘서 접근권한을 설정할 수 있는데,
한가지 의문이 든 점은 모든 주소에 따로따로 권한 설정을 해주어야 하는지 입니다.
또한 java에 정규식이 있듯이 비슷한 방법으로 주소를 효율적으로 적을 수 있을지 궁금했습니다.
🔥 해결 방법
1. 우선순위
적용되는 우선순위는 간단했습니다.
상단에 위치하면 api 주소의 우선순위가 높습니다.
.antMatchers("/api/v1/signup") .anonymous() .antMatchers("/api/v1/logout") .access("hasRole('ROLE_USER') or hasRole('ROLE_BUSINESS')") .antMatchers("/api/v1/login") .anyRequest() .permitAll();
다음처럼 설정할 경우 signup 페이지와 logout 페이지를 제외한 다른 모든 request들은 permitAll() 처리 됩니다.
2. Ant Style Pattern
url 매핑에는 ant pattern이 사용된다.
? : 1개의 문자와 매칭 (matches single character) * : 0개 이상의 문자와 매칭 (matches zero or more characters) ** : 0개 이상의 디렉토리와 파일 매칭 (matches all files / directories)
그렇기 때문에 REST하게 작성한 주소를 바탕으로 긴 주소에서 부터 짧은 주소로 겹치지 않게 작성해야한다.
.antMatchers(HttpMethod.POST, "/api/v1/events/*/reviews") .access("hasRole('ROLE_USER')") .antMatchers(HttpMethod.PATCH, "/api/v1/events/*") .access("hasRole('ROLE_BUSINESS')") .antMatchers(HttpMethod.POST, "/api/v1/events") .access("hasRole('ROLE_BUSINESS')")
3. Method별 권한
같은 api 주소이지만 method에 따라서 접근 권한이 다를 수 있다.
.antMatchers(HttpMethod.GET, "/api/v1/markets/*") .access("hasRole('ROLE_USER') or hasRole('ROLE_BUSINESS')") .antMatchers(HttpMethod.PATCH, "/api/v1/markets/*") .access("hasRole('ROLE_BUSINESS')") .antMatchers(HttpMethod.POST, "/api/v1/markets") .access("hasRole('ROLE_USER')") .antMatchers(HttpMethod.GET, "/api/v1/markets")