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)
实际上,解决方案只是为 google 身份验证添加另一个属性:
spring.security.oauth2.client.registration.google.scope=profile email
Run Code Online (Sandbox Code Playgroud)
不确定,默认范围是什么,以及为什么服务入口取决于范围,但没有这一行代码永远不会到达我的自定义服务。
| 归档时间: |
|
| 查看次数: |
2032 次 |
| 最近记录: |