I get some error when use trace in server look like:
2023-10-13T08:56:09.091Z TRACE 17872 --- [nio-3009-exec-1] estMatcherDelegatingAuthorizationManager : Checking authorization on SecurityContextHolderAwareRequestWrapper[ FirewalledRequest[ org.apache.catalina.core.ApplicationHttpRequest@2f5acb7e]] using org.springframework.security.authorization.AuthenticatedAuthorizationManager@6f8fd87a
2023-10-13T08:56:09.091Z TRACE 17872 --- [nio-3009-exec-1] .s.s.w.c.SupplierDeferredSecurityContext : Created SecurityContextImpl [Null authentication]
2023-10-13T08:56:09.091Z TRACE 17872 --- [nio-3009-exec-1] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to AnonymousAuthenticationToken [Principal=anonymousUser, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=42.113.156.80, SessionId=8EA96F167C803A5FCF2AB192EE519EF7], Granted Authorities=[ROLE_ANONYMOUS]]
2023-10-13T08:56:09.091Z TRACE 17872 --- [nio-3009-exec-1] o.s.s.w.a.ExceptionTranslationFilter : Sending AnonymousAuthenticationToken [Principal=anonymousUser, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=42.113.156.80, SessionId=8EA96F167C803A5FCF2AB192EE519EF7], Granted Authorities=[ROLE_ANONYMOUS]] to authentication entry point since access is denied
org.springframework.security.access.AccessDeniedException: Access Denied
When I run it locally, everything works fine. This is my config:
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final AuthenticationService authenticationService;
private final UserDetailsService userDetailsService;
@Override
protected void doFilterInternal(
@NonNull HttpServletRequest request,
@NonNull HttpServletResponse response,
@NonNull FilterChain filterChain)
throws ServletException, IOException {
final String authHeader = request.getHeader("Authorization");
final String token;
final String userEmail;
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
filterChain.doFilter(request, response);
return;
}
token = authHeader.substring(7);
Claims claims = authenticationService.extractAllClaims(token);
userEmail = claims.getSubject();
if (userEmail != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(userEmail);
if (authenticationService.isTokenValid(token, userDetails)) {
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
}
}
filterChain.doFilter(request, response);
}
}
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
private final JwtAuthenticationFilter jwtAuthenticationFilter;
private final AuthenticationProvider authenticationProvider;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf(httpSecurityCsrfConfigurer -> httpSecurityCsrfConfigurer.ignoringRequestMatchers("/**"))
.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry
.requestMatchers("/api/authentication/**",
"/v2/api-docs",
"/v3/api-docs",
"/v3/api-docs/**",
"/swagger-resources",
"/swagger-resources/**",
"/configuration/ui",
"/configuration/security",
"/swagger-ui/**",
"/webjars/**",
"/swagger-ui.html"
)
.permitAll()
.anyRequest()
.authenticated()
)
.exceptionHandling(httpSecurityExceptionHandlingConfigurer -> httpSecurityExceptionHandlingConfigurer.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)))
.sessionManagement(httpSecuritySessionManagementConfigurer -> httpSecuritySessionManagementConfigurer
.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authenticationProvider(authenticationProvider)
.addFilterBefore(jwtAuthenticationFilter, BasicAuthenticationFilter.class);
return http.build();
}
}
Am I missing any configuration? Thanks
Comment From: sjohnr
Thanks for getting in touch, but it feels like this is a question that would be better suited to Stack Overflow. We prefer to use GitHub issues only for bugs and enhancements. Feel free to update this issue with a link to the re-posted question (so that other people can find it) or add a minimal sample that reproduces this issue if you feel this is a genuine bug.
Please note that a custom filter should not be part of the minimal sample.
Comment From: mouhib1agrebi
@KhanamDEV @sjohnr please any updates I've the same issue
Comment From: yelog
@mouhib1agrebi I just encountered this issue myself and came across this discussion during my investigation. I eventually resolved the problem, so I’m posting it here for reference.
In my architecture using Spring Cloud, the gateway was incorrectly configured to allow anonymous access to this endpoint. The issue was that the endpoint had permission checks with @PreAuthorize("hasAnyAuthority('sys:oss')"). As a result, when the gateway called the microservice, it lost the Authorization header, causing org.springframework.security.access.expression.SecurityExpressionRoot#getAuthoritySet to return the anonymous user’s authorities as ['ROLE_ANONYMOUS']. This led to the authorization error.