我是Java Spring的新手,我想自定义oauth2响应数据以添加用户数据,但是这对我和我的数据响应来说都很困难

{
  "access_token": "4024beac-bc3d-463c-8225-4183e7d8a057",
   "token_type": "bearer",
   "refresh_token": "5d748d08-ca89-4de2-a2ac-0de2043ee53e",
   "expires_in": 298,
   "scope": "read write"
}


我想要这样

{
"access_token": "4024beac-bc3d-463c-8225-4183e7d8a057",
"token_type": "bearer",
"refresh_token": "5d748d08-ca89-4de2-a2ac-0de2043ee53e",
"expires_in": 298,
"scope": "read write",
"myUserData": {"id" : 1,"firstName": "Hiku","lastname": "Saing"}
}


这是我的代码3文件配置

public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
            .withClient("admin").secret(bCryptPasswordEncoder.encode("123"))
            .authorizedGrantTypes("password", "refresh_token")
            .scopes("read", "write")
            .accessTokenValiditySeconds(5 * 60)
            .refreshTokenValiditySeconds(10 * 60);
    }
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager);
        endpoints.pathMapping("/oauth/token", "/login/**");
    }
}

public class ResourceServiceConfig extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.anonymous().disable()
            .authorizeRequests().antMatchers("/oauth/token", "/login/**", "/register").permitAll()
            .and()
            .authorizeRequests().antMatchers("/api/**")
            .authenticated()
            .and()
            .exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
    }
}
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserServiceLoginImp userService;
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();

    }
    @Override
    protected void configure (AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(encoder());
    }
    @Bean
    public BCryptPasswordEncoder encoder() {
        return new BCryptPasswordEncoder();
    }
}


请任何人都可以帮助我。

最佳答案

您可以使用TokenEnhancer将自定义内容添加到令牌中

您可以在@Configuration类中定义它:

endpoints.tokenEnhancer(yourTokenEnhancer)

yourTokenEnhancer必须是实现org.springframework.security.oauth2.provider.token.TokenEnhancer接口的类型。

无论如何,请注意,这是一个令牌增强器,因此您不应将其用作用户信息提供者。

关于java - Spring自定义oauth2响应数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57769030/

10-09 06:54