【问题标题】:Add new field in Spring Boot Oauth2 response在 Spring Boot Oauth2 响应中添加新字段
【发布时间】:2020-04-14 15:21:36
【问题描述】:

我使用了 Spring Boot Oauth2 身份验证并且工作正常。我需要添加带有 Oauth2 响应的 usertype 字段。

我的代码如下。

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

static final String CLIEN_ID = "client";
//static final String CLIENT_SECRET = "devglan";
static final String CLIENT_SECRET = "$2a$04$e/c1/RfsWuTh/vj/BfG";
static final String GRANT_TYPE = "password";
static final String AUTHORIZATION_CODE = "authorization_code";
static final String REFRESH_TOKEN = "refresh_token";
static final String IMPLICIT = "implicit";
static final String SCOPE_READ = "read";
static final String SCOPE_WRITE = "write";
static final String TRUST = "trust";
static final int ACCESS_TOKEN_VALIDITY_SECONDS = 50*60*60;
static final int FREFRESH_TOKEN_VALIDITY_SECONDS = 66*60*60;

@Autowired
private TokenStore tokenStore;

@Autowired
private AuthenticationManager authenticationManager;

@Override
public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {

    configurer
            .inMemory()
            .withClient(CLIEN_ID)
            .secret(CLIENT_SECRET)
            .authorizedGrantTypes(GRANT_TYPE, AUTHORIZATION_CODE, REFRESH_TOKEN, IMPLICIT )
            .scopes(SCOPE_READ, SCOPE_WRITE, TRUST)
            .accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS).
            refreshTokenValiditySeconds(FREFRESH_TOKEN_VALIDITY_SECONDS);
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    endpoints.tokenStore(tokenStore)
            .authenticationManager(authenticationManager);
}
 }

下面给出认证后的响应

{"access_token":"b3336423-ed9d-4d91-a308-2a5d16dbc037","token_type":"bearer","refresh_token":"135f6f95-8f5b-404a-83fc-11e12bf772be","expires_in":179999,"scope":"read write trust"}

我需要在上面的响应中添加 usertype 字段。

【问题讨论】:

    标签: spring-boot spring-oauth2


    【解决方案1】:

    我得到了解决方案 创建 CustomTokenConverter

    @Component
    public class CustomTokenConverter extends JwtAccessTokenConverter {
    
        @Autowired
        private UserRepository userRepository;
    
        @Override
        public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    
            final Map<String, Object> additionalInfo = new HashMap<>();
            User user = userRepository.findByUsername(authentication.getName());
    
            additionalInfo.put("usertype", user.getTypeOfUser());
    
            ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
    
            return super.enhance(accessToken, authentication);
        }
    
    }
    

    并更新 AuthorizationServerConfig

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
            endpoints.tokenStore(tokenStore)
                    .tokenEnhancer(customTokenEnhancer())
                    .authenticationManager(authenticationManager);
        }
        
    
        @Bean
        public CustomTokenConverter customTokenEnhancer() {
            return new CustomTokenConverter();
        }
    

    现在我得到了这样的回应

    {"access_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJhZG1pbiIsInNjb3BlIjpbInJlYWQiLCJ3cml0ZSIsInRydXN0Il0sInVzZXJ0eXBlIjoiQWRtaW4iLCJleHAiOjE1NzcyODA3ODYsImF1dGhvcml0aWVzIjpbIlJPTEVfQURNSU4iXSwianRpIjoiZDk4MTkxOWYtZDMzOC00YTE2LTk4NTEtYWFjODUzZWYyOGE4IiwiY2xpZW50X2lkIjoiZGV2Z2xhbi1jbGllbnQifQ.BuuVK6HFajOM9vryciwBi6-aMSMOrV5E0YiPyPmZ0Uw","token_type":"bearer","refresh_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJhZG1pbiIsInNjb3BlIjpbInJlYWQiLCJ3cml0ZSIsInRydXN0Il0sImF0aSI6ImQ5ODE5MTlmLWQzMzgtNGExNi05ODUxLWFhYzg1M2VmMjhhOCIsInVzZXJ0eXBlIjoiQWRtaW4iLCJleHAiOjE1NzczMzgzODYsImF1dGhvcml0aWVzIjpbIlJPTEVfQURNSU4iXSwianRpIjoiZGNjYTEyZDUtNzY1Ny00N2I5LThkYmMtNTkzOWQzZDk3MWYzIiwiY2xpZW50X2lkIjoiZGV2Z2xhbi1jbGllbnQifQ.L_vguBCDOeAGNlq-L-OiPO6TW2gRXNBv562JnyR3uSE","expires_in":179999,"scope":"read write trust","usertype":"Admin","jti":"d981919f-d338-4a16-9851-aac853ef28a8"}
    

    谢谢

    【讨论】:

      【解决方案2】:

      虽然前面的方法没有任何问题,但您也可以使用UserDetailsCustomTokenConverter 类中保存对database 的额外调用。

      @Component
      public class CustomTokenConverter extends JwtAccessTokenConverter {
      
           @Override
           public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
      
               final Map<String, Object> additionalInfo = new HashMap<>();
               CustomUserDetail principal = (CustomUserDetail) authentication.getPrincipal();
      
               additionalInfo.put("usertype", principal.getUserType());
      
               ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
      
               return super.enhance(accessToken, authentication);
           }
      }
      

      在这种情况下,您需要在 CustomUserDetail 类中添加 userType 属性

      public class CustomUserDetail implements UserDetails {
      
          private String userType;
          
          // ....
      
          public CustomUserDetails(User user) {
               this.userType = user.getUserType();
          }
        
          public String getUserType(){
               return this.userType;
          }
          // ....
          
      }
      

      【讨论】:

        猜你喜欢
        • 2021-02-07
        • 2021-01-07
        • 1970-01-01
        • 2019-12-15
        • 1970-01-01
        • 1970-01-01
        • 2020-11-22
        • 2021-03-21
        • 2019-05-24
        相关资源
        最近更新 更多