springcloud + zuul + oauth2
@Configuration
@EnableAuthorizationServer
public class OAuth2AuthServerConfig extends AuthorizationServerConfigurerAdapter{
@Autowired
public CustomWebResponseExceptionTranslator customWebResponseExceptionTranslator;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private DataSource dataSource;
@Bean
public TokenStore tokenStore(){
return new JwtTokenStore(jwtTokenEnhancer());
}
@Bean
public JwtAccessTokenConverter jwtTokenEnhancer() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("weijie.key"),"weijie".toCharArray());
converter.setKeyPair(keyStoreKeyFactory.getKeyPair("weijie"));
return converter;
}
/**
* 用户合法性校验
* @param endpoints
* @throws Exception
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.exceptionTranslator(customWebResponseExceptionTranslator)
.userDetailsService(userDetailsService)
.tokenStore(tokenStore())
.tokenEnhancer(jwtTokenEnhancer())
.authenticationManager(authenticationManager);
}
/**
* 配置客户端应用详细信息
* @param clients
* @throws Exception
*/
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.jdbc(dataSource);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.tokenKeyAccess("isAuthenticated()")
.checkTokenAccess("isAuthenticated()");
}
}
@Component
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private LoginUserMapper loginUserMapper;
//这就是构建用户所必需的的三个属性。用户名、密码、权限、
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
LoginUser loginUser = loginUserMapper.selectOne(new QueryWrapper<LoginUser>().eq("username",username));
return loginUser;
}
}
@GetMapping("role")
public Result getRoleMenus(@AuthenticationPrincipal String username){
List<Menu> menus = menuService.getRoleMenus(username);
return Result.success(menus);
}
为什么SecurityContextHolder.getContext().getAuthentication().getPrincipal();和@AuthenticationPrincipal 注解都只能获取当前用户的用户名? 怎么配置可以获取 用户ID等信息呢?
题主,这个问题我来替你解决,若有帮助,还望采纳,点击回答右侧采纳即可。
在使用 Zuul 搭建微服务网关时,通常会与 OAuth2 进行集成,以实现安全认证和访问控制。在获取当前用户信息方面,可以通过 OAuth2 认证服务器提供的 /userinfo 接口来获取用户信息。
但是,有的时候只能获取到用户名的原因可能是因为 OAuth2 认证服务器没有返回更多的用户信息。这取决于认证服务器的具体设置和配置。有些 OAuth2 认证服务器可能只返回用户名,而不返回其他用户信息。如果需要获取更多的用户信息,可以在认证服务器的配置中进行相应的修改。