Correct way to check the existance of a user in a database after OAuth2 authentication

Viewed 217

i am working on a web application using SpringBoot and OAuth2 that requires just the authentication by google. It can allow acces just to the members of my uni but not any member, they have to be registered in a database, specifically their emails. So i created an entity class User:

User(id, email, role)

In this table the user with the role ADMIN could add users, delete them and update their role so it must have a different dashboard than a regular user. I started creating my custom OAuthUser, in this i just store the name and the email from the authenticated user. With the Google restrictions it allows just members of my organization so here i have to implement the function that is going to check if the email of that authenticated user is in the database, after that check his role and allow acces to the different functionalities. And this is the part where i'm stucked, I don't know how to check the existence of that email in the database.

This is my CustomOAuthUser:

    private OAuth2User oAuth2User;

    public CustomOAuth2User(OAuth2User oAuth2User) {
        this.oAuth2User = oAuth2User;
    }

    @Override
    public Map<String, Object> getAttributes() {
        return oAuth2User.getAttributes();
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return oAuth2User.getAuthorities();
    }

    @Override
    public String getName() {
        return oAuth2User.getAttribute("name");
    }

    public String getFullname(){
        return oAuth2User.getAttribute("name");
    }

    public String getEmail(){
        return oAuth2User.<String>getAttribute("email");
    }
}

And this is my WebSecurity configuration:

public class WebSecurity extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http.authorizeRequests()
                .antMatchers("/user/**").hasAnyRole("ADMIN", "USER")
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/index", "/login", "/oauth/**").permitAll()
                .and()
                .oauth2Login()
                .loginPage("/login")
                .userInfoEndpoint()
                .userService(customOAuthUserService);
    }

    @Autowired
    private CustomOAuthUserService customOAuthUserService;
}

I have not found any way to check the existence of the email in the database after getting the google info using this function. I would appreciate any kind of help, maybe there's a better way to do what im trying to do here. This would be my user entity:

public class User {

    @Id
    @Column(nullable = false, updatable = false)
    private Long id;

    @Column(nullable = false, updatable = false)
    private String email;

    @Column(nullable = false)
    private String role;
}

In my user repository i implemented the next query:

    @Query("SELECT s FROM User s WHERE s.email=?1")
    Optional<User> findUserByEmail(String email);

Thanks in advance.

1 Answers

Not sure if you're still looking for a solution but this is how I checked if email exists in the database.

Edit your CustomOAuth2UserService.java as follows:

    @Override
    public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException
    {
        String clientName = userRequest.getClientRegistration().getClientName();
        OAuth2User user = super.loadUser(userRequest);

        CustomOAuth2User customOAuth2User = new CustomOAuth2User(user, clientName);
        String email = customOAuth2User.getEmail();

        Optional<User> optionalUser = userRepository.findUserByEmail(email);
        boolean userExists = optionalUser.isPresent();

        if (userExists) 
        {
            //Your code here
        }

        return customOAuth2User;
    }
Related