title: Adding a custom OidcUserService to work with Spring Azure AAD OidcUserService
body: <p>We have the following Spring Security Configuration class that extends Spring Azure configuration adapter and want to add a custom OidcUserService to the userInfo callback. We have 2 separate projects, a prototype one and our real project. We used the prototype to prove that it can work, and once it worked move it to our real project. Both projects are identical in configuration, pom/libraries on the class path, etc. But in the real project we get an error stating there is a circular dependency in the configuration. We can't figure out how to resolve this problem.</p>
  <p>EDIT: Some more findings, It appears Spring in the real project is injecting our custom OidcUserService into the AADO Security beans instead of using their own, whereas the prototype puts in the correct AADO OidcUserService. Like the order of bean instantiation is different between projects even though we do not specify order in either project.</p>
  <p>Here is the code in both projects for the configuration. The custom OidcUserService is identical to each project. Copy/Pasted from one project to the other, including this configuration.</p>
  <pre><code>@EnableWebSecurity
  @EnableGlobalMethodSecurity(prePostEnabled = true)
  class AADOAuth2LoginSecurityConfig extends AADWebSecurityConfigurerAdapter {
  
  @Resource
  OAuth2UserService&lt;OidcUserRequest, OidcUser&gt; customOidcUserService;
  
  @Override
  protected void configure(HttpSecurity http) throws Exception {
      super.configure(http);
      http
              .authorizeRequests()
              .antMatchers(&quot;/&quot;, &quot;/login&quot;, &quot;/*.js&quot;, &quot;/*.css&quot;).permitAll()
              .anyRequest().authenticated()
              .and()
              .csrf()
              .disable()
              .oauth2Login(oauth2Login -&gt;
                      oauth2Login.userInfoEndpoint(userInfoEndpoint -&gt;
                              userInfoEndpoint.oidcUserService(customOidcUserService)
                      )
              );
  }
  </code></pre>
  <p>}</p>
  <p>Here is the custom service, in case you wanted to see it.</p>
  <pre><code>@Service
  public class CustomOidcUserService implements OAuth2UserService&lt;OidcUserRequest, OidcUser&gt; {
  
  final private OAuth2UserService&lt;OidcUserRequest, OidcUser&gt; aadoAuth2UserService;
  
  public CustomOidcUserService(OAuth2UserService&lt;OidcUserRequest, OidcUser&gt; aadoAuth2UserService) {
      this.aadoAuth2UserService = aadoAuth2UserService;
  }
  
  public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
      OidcUser oidcUser = aadoAuth2UserService.loadUser(userRequest);
      //Custom code would go here
      return oidcUser;
  }
  </code></pre>
  <p>}</p>