'Restrict logins to my oauth App - Spring boot

I have successfully done a OAuth2 login with spring boot and Google, but I'd like to restrict logins to a specific google emails. I want to have them pre-stored in a database, and I want to check if the user is in the database.

If the google user that is not predefined tries to log in, I need to redirect them to the login page and make them try to log in again, and show them that they are restricted.

I have tried comparing the users in OidcUserService, but I don't know if that's the place to do it, and even how to reject the user at that point

public class CustomOidcUserService extends OidcUserService {


    @Autowired
    private UserRepository userRepository;


    @Override
    public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
        OidcUser oidcUser = super.loadUser(userRequest);
        Map attributes = oidcUser.getAttributes();
        GoogleOAuth2UserInfo userInfo = new GoogleOAuth2UserInfo();
        userInfo.setEmail((String) attributes.get("email"));
        userInfo.setId((String) attributes.get("sub"));
        userInfo.setName((String) attributes.get("name"));
        User user = userRepository.findByEmail(userInfo.getEmail());

        if(user == null) {
            throw new OAuth2AuthenticationException("User not found in database");
//Reject the user here and make him log in again?
        }

        System.out.println("User does exist");

        return oidcUser;
    }
}

SecurityConfig

public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private OidcUserService oicdUserService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated()
                .and()
                .oauth2Login()
                .redirectionEndpoint()
                .baseUri("/oauth2/callback/*")
                .and()
                .userInfoEndpoint()
                .oidcUserService(oicdUserService)
                .and()
                .authorizationEndpoint()
                .baseUri("/oauth/authorize")
                .authorizationRequestRepository(customAuthorizationRequestRepository());
    }

     @Bean
    public AuthorizationRequestRepository customAuthorizationRequestRepository() {
        return new HttpSessionOAuth2AuthorizationRequestRepository();
     }

}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source