我有多个为我的oauth2身份验证服务器注册的客户端。我想获得基于clientId的用户权限。假设USER-1具有CLIENT-1的ADMIN权限,而CLIENT-2则具有USER-1的USER权限。
我已经尝试过此issue。但是我总是收到一个空请求。
final HttpServletRequest request = ((ServletRequestAttributes)
RequestContextHolder.getRequestAttributes()).getRequest();
我还添加了一个WebListner,但是没有运气。
@Configuration
@WebListener
public class MyRequestContextListener extends RequestContextListener {
}
@Service
public class DomainUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Autowired
private AuthorityRepository authorityRepository;
@Override
@Transactional
public UserDetails loadUserByUsername(final String email) throws UsernameNotFoundException {
User user = userRepository.findUserByUserName(email);
if (user == null) {
new UsernameNotFoundException("Username not found");
}
String clientId = "?"; // How to get clientId here?
List<String> roles = authorityRepository.getUserAuthorities(email, clientId);
return new DomainUser(email, user.getCredential(), user.getId(), fillUserAuthorities(roles));
}
public Collection<SimpleGrantedAuthority> fillUserAuthorities(Collection<String> roles) {
Collection<SimpleGrantedAuthority> authorties = new ArrayList<SimpleGrantedAuthority>();
for (String role : roles) {
authorties.add(new SimpleGrantedAuthority(role.toUpperCase()));
}
return authorties;
}
}
如果我朝错误的方向前进,那么任何建议都是可以接受的。
答案 0 :(得分:0)
当前,我正在使用自定义JWT令牌增强器来达到要求。但是我不确定这是否是正确的方法。我不确定为什么我认为这是错误的方法。但是您可以使用以下解决方案来实现这一目标。
public class CustomTokenEnhancer implements TokenEnhancer {
@Autowired
private AuthorityRepository authRepository;
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
Map<String, Object> additionalInfo = new HashMap<>();
DomainUser authPrincipal = (DomainUser) authentication.getPrincipal();
List<String> clientBasedRoles = authRepository.getUserAuthorities(authPrincipal.getId(),
authentication.getOAuth2Request().getClientId());
additionalInfo.put("authorities", clientBasedRoles);
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
return accessToken;
}
}
然后,在您的AuthorizationServerConfigurerAdapter中。
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Bean
public TokenEnhancer tokenEnhancer() {
return new CustomTokenEnhancer();
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer(), accessTokenConverter()));
endpoints.authenticationManager(this.authenticationManager).accessTokenConverter(accessTokenConverter())
.tokenEnhancer(tokenEnhancerChain);
}
}