스프링 부트 보안을 구성 할 수 없음-항상 403

Oct 21 2020

그래서 나는 스프링 보안을 구성해야하고 403-금지를 제공하기 때문에 무언가가 누락되었다고 생각합니다. 봄 전문가의 도움을 주시면 감사하겠습니다!

솔루션에 집중하기 위해 좀 더 간단하게 만들었습니다. 원본 코드는 더 복잡하지만 오류는 여전히 동일합니다.

@EnableWebSecurity
public class WebSecurityConfig {

    @Configuration
    @Order(1)
    public static class JWTSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .csrf()
                        .disable()
                    .sessionManagement()
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                        .and()
                    .exceptionHandling()
                        .authenticationEntryPoint(WebSecurityConfig::handleException)
                        .and()
                    .addFilterAfter(new JWTAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class)
                    .authorizeRequests()
                        .antMatchers("/images/**")
                        .hasAnyRole("MY_USER", "MY_ADMIN")
                        .anyRequest()
                    .authenticated();
        }
    }
}

필터 클래스는 간단하고 거의 수행하지 않습니다.

public class JWTAuthorizationFilter extends OncePerRequestFilter {

    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException {
        try {
                SecurityContextHolder.getContext()
                        .setAuthentication(new UsernamePasswordAuthenticationToken(
                                "John Doe",
                                null,
                                List.of(new SimpleGrantedAuthority("MY_USER")))
                        );
            } catch (Exception e) {
                SecurityContextHolder.clearContext();
            }

            chain.doFilter(request, response);
}

REST 엔드 포인트를 호출 한 후 :

GET http://localhost:8083/images/parcels/parcel1/data

항상 스프링의 기본 403 응답으로 끝납니다. 내가 뭘 놓치고 있는지 모르겠다. 어떤 도움이라도 좋을 것입니다.

답변

3 omer Oct 21 2020 at 20:52

new SimpleGrantedAuthority("MY_USER") 역할이 아닌 권한입니다.

hasAnyAuthority("MY_USER", "MY_ADMIN")대신 사용해야 합니다hasAnyRole("MY_USER", "MY_ADMIN")

편집 : 또는 역할 접두사를 사용할 수 있습니다.

private String defaultRolePrefix = "ROLE_";

-

 new SimpleGrantedAuthority("ROLE_MY_USER")