1

I'm trying to get few fields out of user's info when user logs in with Github. Info that I'm trying to get is 'login', 'bio', 'url'. How do I save specific fields to DB?

When I use Authentication authentication = SecurityContextHolder.getContext() .getAuthentication(); authentication.getPrincipal() I get all user's info and don't know how to pull out specific fields. This is a response I'm getting:

    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}]

I also tried casting this to Map but didn't happen.

# 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;
    }

I want to save user's specific fields such as 'login', 'name', 'bio' into my DB.

Russ
  • 41
  • 1
  • 7

1 Answers1

4

Principal object should be instance of 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";
}
S.Step
  • 441
  • 3
  • 8