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

时间:2018-04-08 08:06:28

标签: java spring-boot oauth-2.0 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);
    }
}

我已经用debuger检查过,该应用程序从未实际使用过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");
    }
}

2 个答案:

答案 0 :(得分:1)

我认为您错过了@EnableOAuth2Client课程顶部的SecurityConfig注释。

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

答案 1 :(得分:1)

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

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

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