为什么我的 oauth2 配置没有使用我的自定义 UserService?

Why is my oauth2 config not using my custom UserService?

我正在尝试使用 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");
    }
}

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

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

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

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

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