【问题标题】:Why is my oauth2 config not using my custom UserService?为什么我的 oauth2 配置没有使用我的自定义 UserService?
【发布时间】:2018-09-17 20:07:10
【问题描述】:

我正在尝试使用 google 的身份验证。我用的是springboot2,所以大部分配置都是自动的。身份验证本身运行良好,但之后我想用我自己的数据(角色、用户名和其他内容)填充 Principal。

我创建了扩展 DefaultOauth2UserService 的 MyUserService,我正在尝试按如下方式使用它:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    MyUserService myUserService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .oauth2Login()
                .userInfoEndpoint()
                    .userService(myUserService);
    }
}

我用调试器检查过,该应用程序实际上从未使用 loadUser 方法。这是 MyUserService 的实现:

@Component
public class MyUserService extends DefaultOAuth2UserService {
    @Autowired
    UserRepository userRepository;

    public MyUserService(){
        LoggerFactory.getLogger(MyUserService.class).info("initializing user service");
    }

    @Override
    public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
        OAuth2User oAuth2User = super.loadUser(userRequest);
        Map<String, Object> attributes = oAuth2User.getAttributes();

        String emailFromGoogle = (String) attributes.get("email");
        User user = userRepository.findByEmail(emailFromGoogle);
        attributes.put("given_name", user.getFirstName());
        attributes.put("family_name", user.getLastName());

        Set<GrantedAuthority> authoritySet = new HashSet<>(oAuth2User.getAuthorities());

        return new DefaultOAuth2User(authoritySet, attributes, "sub");
    }
}

【问题讨论】:

    标签: java spring-boot oauth-2.0 spring-security-oauth2


    【解决方案1】:

    实际上解决方案只是为 google 身份验证添加另一个属性:

    spring.security.oauth2.client.registration.google.scope=profile email
    

    不确定,默认范围是什么,以及为什么服务的入口取决于范围,但没有这一行代码永远不会到达我的自定义服务。

    【讨论】:

    • 答案是默认情况下,如果您在配置 Google OAuth2 客户端时不提供任何范围,Spring Boot 将使用 CommonOAuth2Provider 类中提供的默认值。默认范围是:openid、profile、email。通过包含 openid 范围,Spring Boot 将使用 OAuth2UserService 接口的 OidcUserService 实现,而不是 DefaultOAuth2UserService。所以你应该扩展 OidcUserService。并配置它
    • 是否有任何方法可以强制在 DefaultOAuth2UserService 上使用 OidcUserService 而无需添加 openid 范围?
    【解决方案2】:

    我认为您缺少 @EnableOAuth2Client 类顶部的 SecurityConfig 注释。

    无论如何,如果有帮助,我在https://github.com/TwinProduction/spring-security-oauth2-client-example/ 为 oauth2 制作了一个自定义用户服务的示例

    【讨论】:

    • 非常感谢!尽管这不是解决方案,但您的项目绝对帮助我解决了它。我将把它写在单独的答案中,所以很容易找到是否有人会遇到同样的问题。
    猜你喜欢
    • 2016-12-12
    • 2011-09-15
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多