Search code examples
javaspring-bootspring-securityjwt

Spring Security issue with JWT: Cannot subclass final class JwtAuthenticationProvider


I would appreciate your help with resolving this issue. I have an application (appA) developed with spring-boot 3.2.5. This application has another module (moduleA) which implements Spring Security's resource server (spring-boot-starter-oauth2-resource-server). Whenever I try to start the application, I get this error:

Error creating bean with name
'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration':
Unsatisfied dependency expressed through method 'setFilterChains'
parameter 0: Error creating bean with name
'oAuth2ResourceServerFilterChain' defined in class path resource
[com/modulea/oauth2resourceserver/config/Oauth2ResourceServerConfig.class]:
Failed to instantiate
[org.springframework.security.web.SecurityFilterChain]: Factory method
'oAuth2ResourceServerFilterChain' threw exception with message: Could
not postProcess
 org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationProvider@26f1b53b of type class
org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationProvider

Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'oAuth2ResourceServerFilterChain'
defined in class path resource
[oauth2resourceserver/config/Oauth2ResourceServerConfig.class]: Failed
to instantiate [org.springframework.security.web.SecurityFilterChain]:
Factory method 'oAuth2ResourceServerFilterChain' threw exception with
message: Could not postProcess

org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationProvider@26f1b53b of type class
 org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationProvider
    at
 org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:648)
~[spring-beans-6.1.6.jar:6.1.6]

Project Structure

1. AppA's pom

    <dependency>
      <groupId>com.modulea</groupId>
      <artifactId>oauth2-resourceserver</artifactId>
      <version>0.0.1-SNAPSHOT</version>
    </dependency>

2. Module A
 - src
   - main
     - com
       - modulea
         - oauth2resourceserver
           - config
             - Oauth2ResourceServerConfig
             - RsaKeyProperties
             - DecoderEncoderConfig

Oauth2ResourceServerConfig

    package com.modulea.oauth2resourceserver.config;
    
    import lombok.AccessLevel;
    import lombok.RequiredArgsConstructor;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.core.annotation.Order;
    import org.springframework.security.config.Customizer;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
    
    import org.springframework.security.config.http.SessionCreationPolicy;
    import org.springframework.security.oauth2.jwt.JwtDecoder;
    import org.springframework.security.web.SecurityFilterChain;
    import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
    
    @RequiredArgsConstructor(access = AccessLevel.PROTECTED, onConstructor_ = {@Autowired})
    @Configuration
    public class Oauth2ResourceServerConfig {
        private final JwtDecoder jwtDecoder;
    
        @Order(4)
        @Bean
        public SecurityFilterChain oAuth2ResourceServerFilterChain(HttpSecurity http) throws Exception {
            HttpSessionRequestCache requestCache = new HttpSessionRequestCache();
            requestCache.setMatchingRequestParameterName(null);
            http
                    .csrf(AbstractHttpConfigurer::disable)
                    .authorizeHttpRequests(authorize -> authorize
                            .requestMatchers("/internal/**")
                                    .permitAll()
                            .anyRequest()
                                    .authenticated())
                    .oauth2ResourceServer(oAuth2ResourceServerConfigurer -> oAuth2ResourceServerConfigurer.jwt(Customizer.withDefaults()))
                    .sessionManagement(sessionManagement -> sessionManagement
                            .sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                    .httpBasic(Customizer.withDefaults());
            return http
                    .build();
        }
    }

RsaKeyProperties

    package com.modulea.oauth2resourceserver.config;
    
    import org.springframework.boot.context.properties.ConfigurationProperties;
    
    import java.security.interfaces.RSAPrivateKey;
    import java.security.interfaces.RSAPublicKey;
    
    @ConfigurationProperties(prefix = "rsa")
    public record RsaKeyProperties(RSAPublicKey publicKey, RSAPrivateKey privateKey) {
    }

DecoderEncoderConfig

    package com.modulea.oauth2resourceserver.config;
    
    import com.nimbusds.jose.jwk.JWK;
    import com.nimbusds.jose.jwk.JWKSet;
    import com.nimbusds.jose.jwk.RSAKey;
    import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
    import com.nimbusds.jose.jwk.source.JWKSource;
    import com.nimbusds.jose.proc.SecurityContext;
    import lombok.RequiredArgsConstructor;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.oauth2.jwt.JwtDecoder;
    import org.springframework.security.oauth2.jwt.JwtEncoder;
    import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
    import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
    
    @EnableConfigurationProperties({RsaKeyProperties.class})
    @RequiredArgsConstructor
    @Configuration
    public class DecoderEncoderConfig {
    
        private final RsaKeyProperties rsaKeyProperties;
    
        @Bean
        public JwtDecoder jwtDecoder() {
            return NimbusJwtDecoder.withPublicKey(rsaKeyProperties.publicKey()).build();
        }
    
        @Bean
        public JwtEncoder jwtEncoder() {
            JWK jwk = new RSAKey.Builder(rsaKeyProperties.publicKey()).privateKey(rsaKeyProperties.privateKey()).build();
            JWKSource<SecurityContext> jwkSource = new ImmutableJWKSet<>(new JWKSet(jwk));
            return new NimbusJwtEncoder(jwkSource);
        }
    }

Solution

  • The issue is due to Spring's CGLIB's proxy trying to create dynamic proxies in my case, for beans in the configuration class. I decided to go with an architectural redesign to have the resource server as standalone.