繁体   English   中英

Spring自定义oauth2响应数据

[英]Spring custom oauth2 response data

我是 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接口的类型。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM