Проблема Spring Security с JWT: невозможно создать подкласс финального класса JwtAuthenticationProviderJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Проблема Spring Security с JWT: невозможно создать подкласс финального класса JwtAuthenticationProvider

Сообщение Anonymous »

Буду признателен за помощь в решении этой проблемы. У меня есть приложение (appA), разработанное с помощью Spring-Boot 3.2.5. В этом приложении есть еще один модуль (moduleA), который реализует сервер ресурсов Spring Security (spring-boot-starter-oauth2-resource-server). Всякий раз, когда я пытаюсь запустить приложение, я получаю эту ошибку:
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


com.modulea
oauth2-resourceserver
0.0.1-SNAPSHOT


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 jwkSource = new ImmutableJWKSet(new JWKSet(jwk));
return new NimbusJwtEncoder(jwkSource);
}
}


Подробнее здесь: https://stackoverflow.com/questions/786 ... icationpro
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»