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

Mac*_*iak 4 java oauth-2.0 spring-boot spring-security-oauth2

我正在尝试使用谷歌的身份验证。我用的是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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经用调试器检查过,该应用程序实际上从未使用过 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");
    }
}
Run Code Online (Sandbox Code Playgroud)

Mac*_*iak 8

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

spring.security.oauth2.client.registration.google.scope=profile email
Run Code Online (Sandbox Code Playgroud)

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

  • 答案是,默认情况下,如果您在配置 Google OAuth2 客户端时不提供任何范围,Spring Boot 将使用 CommonOAuth2Provider 类中提供的默认值。默认范围是:openid、profile、email。通过包含 openid 范围,Spring Boot 将使用 OAuth2UserService 接口的 OidcUserService 实现,而不是 DefaultOAuth2UserService。所以你应该扩展 OidcUserService。并配置它 (4认同)