programing

access_token JWT에서 데이터를 추가하는 방법

oldcodes 2023. 8. 7. 23:07
반응형

access_token JWT에서 데이터를 추가하는 방법

JWT 토큰에 새 필드를 추가하려고 하는데, 실제로는access_token로 생성되는grant_type=password허가 유형이 다음인 경우에만 필드를 추가합니다.password.

사용자 지정 토큰 인핸서를 구현하면 oauth 로그인 api의 응답 본문에 새 필드를 추가합니다.하지만 나는 그 새로운 필드들만 안에 있으면 됩니다.access_tokenJWT.

예:

해독할 때access_token개체는 원본이어야 합니다.

{
  "user_name": "uuid",
  "scope": [
    "trust"
  ],
  "exp": 1522008499,
  "authorities": [
    "USER"
  ],
  "jti": "9d827f63-99ba-4fc1-a838-bc74331cf660",
  "client_id": "myClient"
}

로.

{
  "user_name": "uuid",
  "newField": [
    {
      "newFieldChild": "1",
    },
    {
      "newFieldChild": "2",
    }
  ],
  "scope": [
    "trust"
  ],
  "exp": 1522008499,
  "authorities": [
    "USER"
  ],
  "jti": "9d827f63-99ba-4fc1-a838-bc74331cf660",
  "client_id": "myClient"
}

구현CustomTokenEnhancer추가newField로그인의 응답 본문에 있는 목록:

{
    "access_token": "jwt-access_token",
    "token_type": "bearer",
    "refresh_token": "jwt-refresh_token",
    "expires_in": 299999,
    "scope": "trust",
    "jti": "b23affb3-39d3-408a-bedb-132g6de15d7",
    "newField": [
      {
        "newFieldChild": "1",
      },
      {
        "newFieldChild": "2",
      }
    ]
}

CustomTokenEnhancer:

public class CustomTokenEnhancer implements TokenEnhancer {
    @Override
    public OAuth2AccessToken enhance(
            OAuth2AccessToken accessToken,
            OAuth2Authentication authentication) {
        Map<String, Object> additionalInfo = new HashMap<>();
        Map<String, String> newFields = ....;
        additionalInfo.put("newField", newFields);
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
        return accessToken;
    }
}

수정이 가능합니까?access_tokenJWT ifgrant_type이라password?

질문이 아래 SO 스레드와 상당히 유사합니다.

Spring OAuth 2 + JWT 추가 정보 포함 액세스 토큰

제가 조금 더 이해하기 쉽게 하겠습니다.두 가지가 있습니다.

  • 추가 정보를 포함하도록 토큰을 향상시키는 액세스 토큰 인핸서
  • 토큰을 API에 표시된 출력으로 변환하는 토큰 컨버터

그래서 당신이 원하는 것은 아래와 같습니다.

  • 액세스 토큰 인핸서는 추가 속성을 확인해야 합니다.
  • 액세스 토큰 변환기에 추가 속성이 표시되지 않아야 합니다.

아래는 제가 실제로 사용한 수업입니다.

package org.baeldung.config;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
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.OAuth2Authentication;
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 static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;

@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServerConfigJwt extends AuthorizationServerConfigurerAdapter {

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("permitAll()")
            .checkTokenAccess("isAuthenticated()");
    }

    @Override
    public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
            .withClient("sampleClientId")
            .authorizedGrantTypes("implicit")
            .scopes("read", "write", "foo", "bar")
            .autoApprove(false)
            .accessTokenValiditySeconds(3600)

            .and()
            .withClient("fooClientIdPassword")
            .secret("secret")
            .authorizedGrantTypes("password", "authorization_code", "refresh_token")
            .scopes("foo", "read", "write")
            .accessTokenValiditySeconds(3600)
            // 1 hour
            .refreshTokenValiditySeconds(2592000)
            // 30 days

            .and()
            .withClient("barClientIdPassword")
            .secret("secret")
            .authorizedGrantTypes("password", "authorization_code", "refresh_token")
            .scopes("bar", "read", "write")
            .accessTokenValiditySeconds(3600)
            // 1 hour
            .refreshTokenValiditySeconds(2592000) // 30 days
        ;
    }

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

    @Override
    public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        final TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(accessTokenConverter()));
        endpoints.tokenStore(tokenStore())
            .tokenEnhancer(tokenEnhancerChain)
            .authenticationManager(authenticationManager);
    }

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

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        final JwtAccessTokenConverter converter = new JwtAccessTokenConverter(){
            @Override
            public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
                if(authentication.getOAuth2Request().getGrantType().equalsIgnoreCase("password")) {
                    final Map<String, Object> additionalInfo = new HashMap<String, Object>();
                    additionalInfo.put("organization", authentication.getName() + randomAlphabetic(4));
                    ((DefaultOAuth2AccessToken) accessToken)
                            .setAdditionalInformation(additionalInfo);
                }
                accessToken = super.enhance(accessToken, authentication);
                ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(new HashMap<>());
                return accessToken;
            }
        };
        // converter.setSigningKey("123");
        final KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("mytest.jks"), "mypass".toCharArray());
        converter.setKeyPair(keyStoreKeyFactory.getKeyPair("mytest"));
        return converter;
    }

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

}

원본 코드는 아래에 있습니다.

https://github.com/Baeldung/spring-security-oauth

변경 사항은 포함되지 않지만 위의 코드로 충분합니다.

테스트

Body

보시다시피 본문에는 추가 속성이 없습니다.

Access token

보다시피 액세스 토큰에는 추가 속성이 있습니다.또한 당신의 요구 사항은 오직grant_type~하듯이password을 통해 충족되는

if(authentication.getOAuth2Request().getGrantType().equalsIgnoreCase("password")) {

언급URL : https://stackoverflow.com/questions/49426086/how-to-add-more-data-in-access-token-jwt

반응형