Spring OAuth2.0:根据客户端 ID 获取用户角色

Ale*_*Man 5 java spring spring-security oauth-2.0 spring-security-oauth2

我为我的 oauth2 身份验证服务器注册了多个客户端。假设user1具有诸如ROLE_A,ROLE_B对于client1 的角色,同一用户具有诸如ROLE_C,ROLE_D对于client2 的角色。现在,当用户使用client1client2登录时,他能够看到所有四个角色,即。ROLE_AROLE_BROLE_CROLE_D

我的要求是当user1登录到client1 时,它应该只返回角色ROLE_AROLE_B. 当他使用client2登录时,它应该只返回ROLE_C并且ROLE_D

为了实现这一点,我计划在身份验证功能中,我需要获取 clientId。因此,使用 clientId 和用户名,我可以从数据库(客户端-用户-角色-映射表)中找到分配给用户的相应角色。.但问题是我不知道如何在身份验证功能中获取clientId

 @Override
    public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
        String userName = ((String) authentication.getPrincipal()).toLowerCase();
        String password = (String) authentication.getCredentials();
        if (userName != null && authentication.getCredentials() != null) {
                String clientId = // HERE HOW TO GET THE CLIENT ID 
                Set<String> userRoles = authRepository.getUserRoleDetails(userName.toLowerCase(), clientId);
                Collection<SimpleGrantedAuthority> authorities = fillUserAuthorities(userRoles);
                Authentication token =  new UsernamePasswordAuthenticationToken(userName, StringUtils.EMPTY, authorities);
                return token;
            } else {
                throw new BadCredentialsException("Authentication Failed!!!");
            }
         } else {
             throw new BadCredentialsException("Username or Password cannot be empty!!!");
         }         
    }
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮我解决这个问题吗

更新 1

CustomAuthenticationProvider.java

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    private final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private LDAPAuthenticationProvider ldapAuthentication;

    @Autowired
    private AuthRepository authRepository;

    public CustomAuthenticationProvider() {
        super();
    }

    @Override
        public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
            String userName = ((String) authentication.getPrincipal()).toLowerCase();
            String password = (String) authentication.getCredentials();
            if (userName != null && authentication.getCredentials() != null) {
                    String clientId = // HERE HOW TO GET THE CLIENT ID 
                    Set<String> userRoles = authRepository.getUserRoleDetails(userName.toLowerCase(), clientId);
                    Collection<SimpleGrantedAuthority> authorities = fillUserAuthorities(userRoles);
                    Authentication token =  new UsernamePasswordAuthenticationToken(userName, StringUtils.EMPTY, authorities);
                    return token;
                } else {
                    throw new BadCredentialsException("Authentication Failed!!!");
                }
             } else {
                 throw new BadCredentialsException("Username or Password cannot be empty!!!");
             }         
    }


    public boolean invokeAuthentication(String username, String password, Boolean isClientValidation) {
        try {
            Map<String, Object> userDetails = ldapAuthentication.authenticateUser(username, password);
            if(Boolean.parseBoolean(userDetails.get("success").toString())) {
                return true;
            }
        } catch (Exception exception) {
            log.error("Exception in invokeAuthentication::: " + exception.getMessage());
        }
        return false;
    }

    @Override
    public boolean supports(Class<? extends Object> authentication) {
        return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
    }

    private Collection<SimpleGrantedAuthority> fillUserAuthorities(Set<String> roles) {
        Collection<SimpleGrantedAuthority> authorties = new ArrayList<SimpleGrantedAuthority>();
        for(String role : roles) {
            authorties.add(new SimpleGrantedAuthority(role));
        }
        return authorties;
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 5

这是修改后的代码

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    String userName = ((String) authentication.getPrincipal()).toLowerCase();
    String password = (String) authentication.getCredentials();
    if (userName != null && authentication.getCredentials() != null) {
            String clientId = getClientId();
            // validate client ID before use
            Set<String> userRoles = authRepository.getUserRoleDetails(userName.toLowerCase(), clientId);
            Collection<SimpleGrantedAuthority> authorities = fillUserAuthorities(userRoles);
            Authentication token =  new UsernamePasswordAuthenticationToken(userName, StringUtils.EMPTY, authorities);
            return token;
        } else {
            throw new BadCredentialsException("Authentication Failed!!!");
        }
     } else {
         throw new BadCredentialsException("Username or Password cannot be empty!!!");
     }         


private  String getClientId(){
    final HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

    final String authorizationHeaderValue = request.getHeader("Authorization");
    final String base64AuthorizationHeader = Optional.ofNullable(authorizationHeaderValue)
            .map(headerValue->headerValue.substring("Basic ".length())).orElse("");

    if(StringUtils.isNotEmpty(base64AuthorizationHeader)){
        String decodedAuthorizationHeader = new String(Base64.getDecoder().decode(base64AuthorizationHeader), Charset.forName("UTF-8"));
        return decodedAuthorizationHeader.split(":")[0];
    }

    return "";
}
Run Code Online (Sandbox Code Playgroud)

有关RequestContextHolder的更多信息