TokenEnhancer добавляет дополнительную информацию не только в jwt, но и в объект ответа - PullRequest
0 голосов
/ 07 февраля 2019

Помогите исключить дополнительную информацию из объекта ответа и добавить только к JWT.

Я добавляю tokenEnhancer, чтобы добавить дополнительную информацию к JWT, но она появляется и в объекте ответа.

{ "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsib2F1dGgyLXJlc291cmNlIl0sImZ1bGxfbmFtZSI6ImhleWJhdCBndWxpeWV2IiwidXNlcl9uYW1lIjoiaGV5YmF0Iiwic2NvcGUiOlsicmVhZCIsIndyaXRlIiwidHJ1c3QiXSwiZXhwIjoxNTQ5NTQxNTkwLCJhdXRob3JpdGllcyI6WyJST0xFX1VTRVIiXSwianRpIjoiY2Y5ZmY0ZDMtOGZiYi00NWFlLWJhMzEtYWM0MjUzNGFjNDI2IiwiY2xpZW50X2lkIjoibXktdHJ1c3RlZC1jbGllbnQifQ.QLVoRxv0kpTx-ruTR55ldMcQzl8M1KGjuWVeNYlH5Ly35vvdA3PvZelYZVpGq0BDr4fHyiUKy-MLP1H0X8_qiT_2onMHTtzvVDa6Wjrx4Ri3q0wOvXQlyFGenz73kxcHkK-YQ8Y8FYKnq3NUBhz-FBFf9JaQOcmsNrrNiF64SlpU3fO2uqbbP6_1_bQ9QHhOHMXxtk0Scz7-gFZm9Ln92K10wd4jLvp1yvSU9X1Hh9lBafB-WAHgVt5eoaZzrbZ7YJYUqNBifoW77NMisNdWIDIqL90jeKBGN6GVm7QRJOo9wNV6tsOLP9-fRgbHu_teqOQe5v_gK3f52xr4jBYs2w", "token_type": "знаменосец", "refresh_token": «eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsib2F1dGgyLXJlc291cmNlIl0sImZ1bGxfbmFtZSI6ImhleWJhdCBndWxpeWV2IiwidXNlcl9uYW1lIjoiaGV5YmF0Iiwic2NvcGUiOlsicmVhZCIsIndyaXRlIiwidHJ1c3QiXSwiYXRpIjoiY2Y5ZmY0ZDMtOGZiYi00NWFlLWJhMzEtYWM0MjUzNGFjNDI2IiwiZXhwIjoxNTQ5NjI3ODEwLCJhdXRob3JpdGllcyI6WyJST0xFX1VTRVIiXSwianRpIjoiMjRkYzliNDEtMTdiMC00ZGQ2LWI3ZTgtODljMWNiNWRmMWQ2IiwiY2xpZW50X2lkIjoibXktdHJ1c3RlZC1jbGllbnQifQ.cIi1yfyNt-komhvduQFPAC098jeEeeqHbiU6HFDNk5uNuvR5HwYkjpKkowvRaLfpXTPGHgpmwNSr3I8LolESLzTfjtPRmFsbrRaLavib5_h32-EpJi5RBKbjhtItxGYbku92K5AxSH9dJ8ceRYg3VQi6zSKrodXXekIdrgtPaGvmEuMcEZF7Oh2qekzvo5u8_1ShZptc76dmAWADMrbHgFxggxioBBOGI27YWvnIPFVLV-RMxrh6FjM_Cy7Tr5BF_13klJvlF2EapkgDQMx0KL53cWvzriZOiDhLcJ6jJk2Cm7oMI5qobcHx7sGD5OC49UYn9LSHQzqh6RqRhckI5g " "expires_in": 179, "Сфера": "чтение доверия записи", "full_name": "Хейбат Гулиев", "JTI":" cf9ff4d3-8fbb-45ae-ba31-ac42534ac426"}

как вы видите, полное имя также появляется в объекте ответа

package com.hqsoft.shop.config;

import com.hqsoft.shop.entities.User;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.util.HashMap;
import java.util.Map;

/****** to add additional info in token structure ******/
public class CustomTokenEnhancer implements TokenEnhancer {
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        User user = (User) authentication.getPrincipal();
        Map<String, Object> map = new HashMap<>();
        map.put("full_name", user.getFullName());
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(map);
        System.out.println(accessToken);
        return accessToken;
    }
}

package com.hqsoft.shop.config;

import com.hqsoft.shop.service.ClientService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
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;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

import java.util.Arrays;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {

    private PasswordEncoder oauthClientPasswordEncoder;
    private AuthenticationManager authenticationManager;
    private ClientService clientService;

    public AuthorizationServer(PasswordEncoder oauthClientPasswordEncoder,
                               AuthenticationManager authenticationManager,
                               ClientService clientService
    ) {
        this.oauthClientPasswordEncoder = oauthClientPasswordEncoder;
        this.authenticationManager = authenticationManager;
        this.clientService = clientService;
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()").passwordEncoder(oauthClientPasswordEncoder);
    }

    /******   for configuring client ******/
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(clientService);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer(), jwtAccessTokenConverter()));

        endpoints
                .tokenStore(tokenStore())
                .authenticationManager(authenticationManager)
                .tokenEnhancer(tokenEnhancerChain);
    }

    @Bean
    public TokenEnhancer tokenEnhancer() {
        return new CustomTokenEnhancer();
    }

    @Bean
    @Primary
    public DefaultTokenServices defaultTokenService() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        defaultTokenServices.setSupportRefreshToken(true);
        return defaultTokenServices;
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    /******   jwt token implementation  ******/
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        Resource resource = new ClassPathResource("keys.jks");
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(resource, "*******".toCharArray());
        jwtAccessTokenConverter.setKeyPair(keyStoreKeyFactory.getKeyPair("mykey"));
        return jwtAccessTokenConverter;
    }
}

1 Ответ

0 голосов
/ 21 февраля 2019

Переопределите метод convertUserAuthentication DefaultUserAuthenticationConverter:

public class CustomUserAuthenticationConverter extends DefaultUserAuthenticationConverter {
   @Override
    public Map<String, ?> convertUserAuthentication(Authentication authentication) {
      Map<String, Object> response = super.convertUserAuthentication(authentication);

      // Add additional info
      User user = (User) authentication.getPrincipal();
      response.put("full_name", user.getFullName());
      return response;
   }
}

В вашей конфигурации создайте новый конвертер токенов и установите его конвертер пользовательских токенов в ваш новый CustomUserAuthenticationConverter, затем используйте этот конвертер токенов в вашем jwtAccessTokenConverter:

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        Resource resource = new ClassPathResource("keys.jks");
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(resource, "*******".toCharArray());
        jwtAccessTokenConverter.setKeyPair(keyStoreKeyFactory.getKeyPair("mykey"));

        // ...
        AccessTokenConverter tokenConverter = new DefaultAccessTokenConverter();
        tokenConverter.setUserTokenConverter(new CustomUserAuthenticationConverter());
        jwtAccessTokenConverter.setAccessTokenConverter(customAccessTokenConverter);
        // ...

        return jwtAccessTokenConverter;
    }

Наконец, используйте только этот конвертер токенов вместо цепочки энхансеров токенов:

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
    endpoints
            .tokenStore(tokenStore())
            .authenticationManager(authenticationManager)
            .tokenConverter(jwtAccessTokenConverter());
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...