Spring OAuth2.0:根据客户端ID获取用户角色 [英] Spring OAuth2.0: Getting User Roles based on Client Id

查看:1921
本文介绍了Spring OAuth2.0:根据客户端ID获取用户角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为oauth2 auth服务器注册了多个客户端。假设 user1 具有 client1 c> ROLE_A , ROLE_B 等角色strong>,同一用户拥有 client2 ROLE_C ROLE_D 等。现在,当用户使用 client1 client2 登录时,他可以看到所有四个角色,即。 ROLE_A ROLE_B ROLE_C ROLE_D

I have multiple clients registered for my oauth2 auth server. lets say user1 have roles such as ROLE_A, ROLE_B for client1, same user has roes such as ROLE_C, ROLE_D for client2. now when the user logins either using client1 or client2 he is able to see all the four roles ie. ROLE_A, ROLE_B, ROLE_C and ROLE_D.

我的要求是当 user1 登录 client1 时应该仅返回角色 ROLE_A ROLE_B 。当他使用 client2 登录时,它应仅返回 ROLE_C ROLE_D

My requirement was when the user1 logins to client1 it should return only the roles ROLE_A and ROLE_B. when he logins using client2 it should return only ROLE_C and ROLE_D

为实现这一目标,我计划的是在身份验证功能中,我需要获取clientId。所以使用clientId和用户名我可以从db(client-user-roles-mapping表)中找到分配给用户的相应角色。 。但问题是我不知道如何在验证功能中获得 clientId

For achieving this, what I planned is within the authenticate function, I need to get the clientId. so using the clientId and the username I can find the corresponding roles allocated to the user from the db (client-user-roles-mapping table). .But the issue is I don't know how to get the clientId within the authenticate function

 @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!!!");
         }         
    }

任何人都可以帮我这个

更新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;
    }
}


推荐答案

这里你是修改后的代码吗?

Here is you code after modification

@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 "";
}

有关 RequestContextHolder

这篇关于Spring OAuth2.0:根据客户端ID获取用户角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆