首页 > 解决方案 > 如何使用 Spring-Boot 2.0 和 OAuth2 登录不同类型的用户

问题描述

我有不同类型的用户要使用单个授权服务器进行身份验证。每个人都有一个数据库表,并将通过不同的客户端登录。我希望能够知道我必须从哪个数据库表中对其进行身份验证。所以我尝试从请求中获取clientID,但我不能。这是我尝试过的:

    @Override
    public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {

        Authentication authentication =  SecurityContextHolder.getContext().getAuthentication();
        String clientID = ((OAuth2Authentication) authentication).getOAuth2Request().getClientId();


        if (clientID.equals("clientID1")){
            //look at the user table
        }
        else if (clientID.equals("clientID2")){
            //look at the company table
        }
        else
            throw new UsernameNotFoundException("ClientID " + clientID + " not found.");
    }

上面的代码编译得很好,但问题发生在运行时,出现如下强制转换异常:

{
    "error": "unauthorized",
    "error_description": "org.springframework.security.authentication.UsernamePasswordAuthenticationToken cannot be cast to org.springframework.security.oauth2.provider.OAuth2Authentication"
}

所以我的问题是:如何从请求中获取 clientID ?或者我可以使用另一种策略来验证我的不同用户吗?任何帮助表示赞赏。

标签: spring-bootspring-security-oauth2

解决方案


推荐阅读