Spring boot — после обновления Spring 1.5 до 2.5 многие методы устарели для OAuth 2.0

После обновления Spring 1.5 до 2.5 многие методы устарели для OAuth 2.0. Я использую аутентификацию на основе токенов JWT.

Устарело -

      import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfiguration;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.AccessTokenConverter;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

Код -

  • Пункт списка

            @Autowired
         OAuthResourceServerSpringConfig oAuthResourceServerSpringConfig;
    
     @Bean
     protected ResourceServerConfiguration oldTokenResource() { // Deprecated - ResourceServerConfiguration
    
     ResourceServerConfiguration resource = new ResourceServerConfiguration() {  
         // Switch off the Spring Boot @Autowired configurers
         public void setConfigurers(List<ResourceServerConfigurer> configurers) {
             super.setConfigurers(configurers);
         }
     };
     resource.setConfigurers(Arrays.<ResourceServerConfigurer> asList(oAuthResourceServerSpringConfig));
     resource.setOrder(3);
    
     return resource;
    

    }

    @AutowiredOAuthJwtResourceServerSpringConfig oAuthJwtResourceServerSpringConfig;

    @Beanprotected ResourceServerConfiguration newJwtResource() { // Устарело — ResourceServerConfiguration

             ResourceServerConfiguration resource = new ResourceServerConfiguration() {  
         // Switch off the Spring Boot @Autowired configurers
         public void setConfigurers(List<ResourceServerConfigurer> configurers) {
             super.setConfigurers(configurers);
         }
     };
     resource.setConfigurers(Arrays.<ResourceServerConfigurer> asList(oAuthJwtResourceServerSpringConfig));
     resource.setOrder(2);
    
     return resource;
    

    }


    Открытый статический класс @Configuration OAuthResourceServerSpringConfig расширяет WebSecurityConfigurerAdapter {

             private final Logger log = LoggerFactory.getLogger(OAuthResourceServerSpringConfig.class);
    
     @Value("${oauth2.server.url}")
     private  String checkTokenUrl;
    
     @Value("${oauth2.server.clientId}") 
     private String clientId;
    
     @Value("${oauth2.server.clientSecret}")
     private String clientSecret;
    
     @Override
     public void configure(HttpSecurity http) throws Exception {
         http.csrf().disable();
             http
             .requestMatcher(new RequestMatcher() {
                 @Override
                 public boolean matches(HttpServletRequest request) {
                     log.info("matching for OAuthResourceServerSpringConfig and header {}",request.getHeader(HEADER_X_JWT));
                     if(request.getHeader(HEADER_X_JWT) == null || !request.getHeader(HEADER_X_JWT).equalsIgnoreCase("yes")) {
                         return true;
                     }
                     return false;
                 }
             })
             .authorizeRequests()
             .antMatchers("/services/myendpoint/**").authenticated();
     }
    
    
    
     @Override
     public void configure(ResourceServerSecurityConfigurer resources) throws Exception { // Deprecated - ResourceServerSecurityConfigurer
         super.configure(resources);
         resources.tokenServices(remoteTokenServices()); // Comment or oauth.server.url
     }
    
    
     /**
      * Default AccessTokenConverter used.
      * 
      * @return DefaultAccessTokenConverter
      */
    
     public AccessTokenConverter accessTokenConverter() { // Deprecated AccessTokenConverter
         DefaultAccessTokenConverter accessTokenConverter = new DefaultAccessTokenConverter();
         DefaultUserAuthenticationConverter userTokenConverter = new DefaultUserAuthenticationConverter();
         accessTokenConverter.setUserTokenConverter(userTokenConverter);
         return accessTokenConverter;
     }
     /**
      * Validate parameters with oauth server.
      * 
      * @param checkTokenUrl - oauth server url
      * @param clientId - id to access server
      * @param clientSecret - secret to access server
      * @return
      */
    
     public RemoteTokenServices remoteTokenServices() { // Deprecated RemoteTokenServices
         final RemoteTokenServices remoteTokenServices = new RemoteTokenServices();
         remoteTokenServices.setCheckTokenEndpointUrl(this.checkTokenUrl);
         remoteTokenServices.setClientId(this.clientId);
         remoteTokenServices.setClientSecret(this.clientSecret);
         remoteTokenServices.setAccessTokenConverter(this.accessTokenConverter());
         return remoteTokenServices;
     }
    

    }

    Открытый статический класс @Configuration OAuthJwtResourceServerSpringConfig расширяет WebSecurityConfigurerAdapter {

             private final Logger log = LoggerFactory.getLogger(OAuthJwtResourceServerSpringConfig.class);
    
     RestTemplate restTemplate = new RestTemplate();
    
     @Value("${workspace.auth.jwt.public.key.url}")
     private String oauthServerJwtPublicKeyUrl;
    
     @Value("${workspace.auth.jwt.aud.url}")
     private String resourceID;       
    
    
    
     @Override
     public void configure(HttpSecurity http) throws Exception {
         http.csrf().disable();
         http
         .requestMatcher(new RequestMatcher() {
             @Override
             public boolean matches(HttpServletRequest request) {
                 log.info("matching for OAuthJwtResourceServerSpringConfig and header {}",request.getHeader(HEADER_X_JWT));
                 if( request.getHeader(HEADER_X_JWT) != null && request.getHeader(HEADER_X_JWT).equalsIgnoreCase("yes") ) {
                     return true;
                 }
                 return false;
             }
         })
         .authorizeRequests()        
         .antMatchers("/services/myendpoint/**").authenticated();
     }
    
     @Override
     public void configure(ResourceServerSecurityConfigurer resources) throws Exception { // Deprecated ResourceServerSecurityConfigurer
          resources.resourceId(resourceID);
          resources.tokenStore(tokenStore());
    
     }
    
    
     public TokenStore tokenStore() throws Exception { // Deprecated TokenStore
         return new JwtTokenStore(jwtTokenEnhancer());
     }
    
    
     protected JwtAccessTokenConverter jwtTokenEnhancer() throws Exception { // Deprecated JwtAccessTokenConverter
         JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
         converter.setVerifierKey(this.getJwtPublicKey());
         //converter.setSigningKey(this.getJwtPublicKey()); //Only for IDP. Not needed for Res Server
         converter.setAccessTokenConverter(this.accessTokenConverter());
         converter.afterPropertiesSet(); //Calling manually as not creating a Bean. It's important
    
         return converter;
     }
    
     public AccessTokenConverter accessTokenConverter() { // Deprecated AccessTokenConverter
         CustomAccessTokenConverter accessTokenConverter = new CustomAccessTokenConverter();
         CustomUserAuthenticationConverter userTokenConverter = new CustomUserAuthenticationConverter();
         accessTokenConverter.setUserTokenConverter(userTokenConverter);
         return accessTokenConverter;
     }
    
     private String getJwtPublicKey() {
         JwtPublicKeyResponse pk =null;
         KeyFactory f;
         try {
             String obj = this.restTemplate.getForObject(this.oauthServerJwtPublicKeyUrl, String.class, new String());
             pk = new Gson().fromJson(obj, JwtPublicKeyResponse.class);
             f = KeyFactory.getInstance("RSA");
             BigInteger modulus = new BigInteger(pk.getMod());
             BigInteger exp = new BigInteger(pk.getExp());
             RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, exp);
             PublicKey pub = f.generatePublic(spec);
             byte[] data = pub.getEncoded();
             String base64encoded = new String(Base64.getEncoder().encode(data));
             base64encoded = "-----BEGIN PUBLIC KEY-----\n" + base64encoded + "\n-----END PUBLIC KEY-----";
             pk.setValue(base64encoded);
         } catch (NoSuchAlgorithmException e) {
             log.error("NoSuchAlgorithmException while validating JWT token" + e);
         } catch (InvalidKeySpecException e) {
             log.error("InvalidKeySpecException while validating JWT token" + e);
         }  catch (Exception e) {
             log.error("InvalidKeySpecException while validating JWT token" + e);
         } 
         if (pk.getValue() == null) {
             throw new RuntimeException(
                 "Error retrieving JWT Public Key. Probably JWT Keystore is not configured in OAuth Server");
         }
         log.debug("JWT Pk:{}", pk.toString());
         return pk.getValue();
     }
    

    }

Могу ли я узнать, как решить эту ошибку? И не могли бы вы сообщить мне, что я могу использовать, чтобы мой API работал.

0 ответов