title: Restrict logins to my oauth App - Spring boot
body: <p>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.</p>
  <p>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.</p>
  <p>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</p>
  <pre><code>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(&quot;email&quot;));
          userInfo.setId((String) attributes.get(&quot;sub&quot;));
          userInfo.setName((String) attributes.get(&quot;name&quot;));
          User user = userRepository.findByEmail(userInfo.getEmail());
  
          if(user == null) {
              throw new OAuth2AuthenticationException(&quot;User not found in database&quot;);
  //Reject the user here and make him log in again?
          }
  
          System.out.println(&quot;User does exist&quot;);
  
          return oidcUser;
      }
  }
  
  </code></pre>
  <p>SecurityConfig</p>
  <pre><code>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(&quot;/oauth2/callback/*&quot;)
                  .and()
                  .userInfoEndpoint()
                  .oidcUserService(oicdUserService)
                  .and()
                  .authorizationEndpoint()
                  .baseUri(&quot;/oauth/authorize&quot;)
                  .authorizationRequestRepository(customAuthorizationRequestRepository());
      }
  
       @Bean
      public AuthorizationRequestRepository customAuthorizationRequestRepository() {
          return new HttpSessionOAuth2AuthorizationRequestRepository();
       }
  
  }
  </code></pre>