SpringBoot 3 OAuth2 Resource Server missing bean of type 'org.springframework.security.oauth2.jwt.JwtDecoder'

1.6k views Asked by At

I made an application with spring-boot-starter-oauth2-resource-server in pom.xml and a value for spring.security.oauth2.resourceserver.jwt.issuer-uri in application.properties. It works fine when I start it for the first time. Then I added a @Service class with org.springframework.security.oauth2.jwt.JwtDecoder injected as below

@Slf4j
@Service
public class MyService {

    private final JwtDecoder jwtDecoder;
    private final WebClient webClient;

    public MyService(
            JwtDecoder jwtDecoder,
            WebClient webClient
    ) {
        this.jwtDecoder = jwtDecoder;
        this.webClient = webClient;
    }

    // method definitions

}

When I run, it throws error

Parameter 0 of constructor in MyService required a bean of type 'org.springframework.security.oauth2.jwt.JwtDecoder' that could not be found.

When I remove the injection it works fine again.

What should I do?

2

There are 2 answers

1
BeLEEver On BEST ANSWER

In a separate config class, You might have to add a bean for the jwt decoder like this:

@Bean
public JwtDecoder jwtDecoder(OAuth2ResourceServerProperties properties) {
    return JwtDecoders.fromIssuerLocation(properties.getJwt().getIssuerUri());
}

The import for the properties would be:

import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;
2
Benaya Trabelsi On

Where is the actual dependency injection? and where does it try to get the value from your application properties? or do you count on auto-configuration? please show the entire flow of your code, looks like some of it is missing. How would Spring boot know where to take the decoder from? you should make sure you have the relevant bean available in the application context, and then use the @Autowired annotation, or use @RequiredArgsConstructor, since you use lombok.