Lib Version
Spring 3.2.4
Spring Security 6.2.3
JJWT 0.12.5

I’m new for utilizing Spring Security and during taking online spring lecture, I encountered this difficulty.

The insructor says I don’t need requestMatchers.authenticated when @PreAuthorized is set.

But @PreAuthorized without requestMatchers doesn’t work.

Signing in and signing up work perfectly.

I’ve tried anything but only this works on purpose.

import ...

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@RequiredArgsConstructor
@Slf4j
public class SecurityConfiguration {
    
    private final JwtAuthenticationFilter jwtAuthenticationFilter;
    
    @Bean
    public AuthenticationManager authenticationManager(
            AuthenticationConfiguration authenticationConfiguration)
            throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }
    
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .httpBasic(AbstractHttpConfigurer::disable)
                .csrf(AbstractHttpConfigurer::disable)
                .sessionManagement(e -> e.sessionCreationPolicy(
                        SessionCreationPolicy.STATELESS))
                .authorizeHttpRequests(e -> {
                    e
                            .requestMatchers("/auth/signin", "/auth/signup")
                            .permitAll();
                    e
                            .requestMatchers(HttpMethod.POST)
                            .authenticated();
                    e
                            .requestMatchers(HttpMethod.GET)
                            .authenticated();
                    e
                            .requestMatchers(HttpMethod.DELETE)
                            .authenticated();
                })
                .addFilterBefore(
                        jwtAuthenticationFilter,
                        UsernamePasswordAuthenticationFilter.class);
        
        return http.build();
    }
    
    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return ((web) -> web.ignoring().requestMatchers("/h2-console/**"));
    }
}
import ...

@AllArgsConstructor
@RequestMapping("/company")
@RestController
public class CompanyController {
    private final CompanyService companyService;
    private final CacheManager redisCacheManager;
    
    @PostMapping
    @PreAuthorize("hasRole('WRITE')")
    public ResponseEntity<?> addCompany(@RequestBody Company request) {
        String ticker = request.getTicker();
        if (ObjectUtils.isEmpty(ticker)) {
            throw new RuntimeException("ticker is empty");
        }
        
        Company company = companyService.save(ticker);
        companyService.addAutocompleteKeyword(company.getName());
        return ResponseEntity.ok(company);
    }
    
    @GetMapping
    @PreAuthorize("hasRole('READ')")
    public ResponseEntity<?> searchCompany(final Pageable pageable) {
        Page<CompanyEntity> allCompany = companyService.getAllCompany(pageable);
        return ResponseEntity.ok(allCompany);
    }
}
import ...

@Component
@RequiredArgsConstructor
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    public static final String TOKEN_HEADER = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer ";
    private final TokenProvider tokenProvider;
    
    @Override
    protected void doFilterInternal(
            HttpServletRequest request, HttpServletResponse response,
            FilterChain filterChain) throws ServletException, IOException {
        String token = resolveTokenFromRequest(request);
        
        if (StringUtils.hasText(token) && tokenProvider.validateToken(token)) {
            Authentication auth = tokenProvider.getAuthentication(
                    token);
            SecurityContextHolder.getContext().setAuthentication(auth);
        }
        
        filterChain.doFilter(request, response);
    }
    
    private String resolveTokenFromRequest(HttpServletRequest request) {
        String token = request.getHeader(TOKEN_HEADER);
        
        if (!ObjectUtils.isEmpty(token) && token.startsWith(TOKEN_PREFIX)) {
            return token.substring(TOKEN_PREFIX.length());
        }
        
        return null;
    }
}

Tried to put @PreAuthorize without requestMatchers.

New contributor

Tuna is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.