当用户使用Github登录时,我试图从用户信息中获取一些字段。我想要获取的信息是'login','bio','url‘。如何将特定字段保存到DB?
当我使用Authentication authentication = SecurityContextHolder.getContext() .getAuthentication(); authentication.getPrincipal()时,我得到了所有用户的信息,而不知道如何提取特定的字段。这是我得到的回复:
Name: [18630847], Granted Authorities: [ROLE_USER], User Attributes:
[login=Blahblah, id=123456789, node_id=4tfg4fg43g,
avatar_url=https://avatars1.githubusercontent.com/u/12345678?v=4,
gravatar_id=, url=https://api.github.com/users/Blahblah,
html_url=https://github.com/blahblah,
followers_url=https://api.github.com/users/blahblah/followers, ......
private_repos=10000}]我也尝试将此转换为Map,但没有实现。
# Databases
spring.h2.console.enabled=true
spring.h2.console.path=/h2
spring.datasource.url=jdbc:h2:mem:test
spring.datasource.username=ruslan
# GitHub
spring.security.oauth2.client.registration.github.client-id=${github-id}
spring.security.oauth2.client.registration.github.client-secret=${github-secret} @GetMapping("/loginSuccess")
public String getLoginInfo(Model model) {
Authentication authentication = SecurityContextHolder.getContext()
.getAuthentication();
model.addAttribute("userd", authentication.getPrincipal().toString());
return "client";
} @Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.anyRequest().authenticated()
.and()
.oauth2Login()
.defaultSuccessUrl("/loginSuccess")
.and()
.logout().logoutSuccessUrl("/index")//permitall
.and()
.csrf().disable()
.headers().frameOptions().disable();
}public interface UserRepository extends JpaRepository<User, Long> {
// User findByUsername(String username);
}@Setter
@Getter
@Entity
public class User {
@Id
@GeneratedValue
private long id;
private String login;
// private String password;
@OneToMany(fetch = FetchType.EAGER, cascade=CascadeType.ALL)
private List<Role> roles;
public User(String login, String password) {
this.login = login;
}我想保存用户的特定字段,如'login','name','bio‘到我的数据库中。
发布于 2019-08-10 22:21:34
主体对象应为OAuth2AuthenticationToken的实例
@GetMapping("/loginSuccess")
public String getLoginInfo(Model model) {
Authentication authentication = SecurityContextHolder.getContext()
.getAuthentication();
//Add this:
Object principal = authentication.getPrincipal();
if(principal instanceof OAuth2AuthenticationToken){
OAuth2AuthenticationToken oAuth2AuthenticationToken = (OAuth2AuthenticationToken)principal;
//By default its DefaultOAuth2User.
OAuth2User oAuth2User = oAuth2AuthenticationToken.getPrincipal();
}
Map<String,Object> attributes = oAuth2User.getAttributes();
//now you can retrieve all attribute values you are interested from attributes map and store or return to view...
// your logic here
return "client";
}https://stackoverflow.com/questions/57434960
复制相似问题