title: How do I get user details in controller of Spring Boot OIDC app?
body: <p>I have adapted the code from <a href="https://www.baeldung.com/spring-security-openid-connect" rel="nofollow noreferrer">here</a> to call a MitreID OIDC server.</p>
  
  <p>My controller:</p>
  
  <pre><code>    public final String home(Principal p) {
      final String username = SecurityContextHolder.getContext().getAuthentication().getName();
  ...
  </code></pre>
  
  <p>returns <code>null</code> and is null for all userdetails.</p>
  
  <p>I have also tried:</p>
  
  <pre><code>public final String home(@AuthenticationPrincipal OpenIdConnectUserDetails user) {
          final String username = user.getUsername();
  </code></pre>
  
  <p>and</p>
  
  <pre><code>@RequestMapping(value = "/username", method = RequestMethod.GET)
      @ResponseBody
      public String currentUserNameSimple(HttpServletRequest request) {
          Principal principal = request.getUserPrincipal();
          return "username: " + principal.getName();
      }
  </code></pre>
  
  <p>Everything is null but the authentication <em>is</em> returning an access and user token.</p>
  
  <p>My security config is:</p>
  
  <pre><code>@Configuration
  @EnableWebSecurity
  public class SecurityConfig extends WebSecurityConfigurerAdapter {
      @Autowired
      private OAuth2RestTemplate restTemplate;
  
      @Override
      public void configure(WebSecurity web) throws Exception {
          web.ignoring().antMatchers("/resources/**");
      }
  
      @Bean
      public OpenIdConnectFilter myFilter() {
  
          final OpenIdConnectFilter filter = new OpenIdConnectFilter("/openid_connect_login");
          filter.setRestTemplate(restTemplate);
          return filter;
      }
  
      @Override
      protected void configure(HttpSecurity http) throws Exception {
  
          // @formatter:off
          http
          .addFilterAfter(new OAuth2ClientContextFilter(), AbstractPreAuthenticatedProcessingFilter.class)
          .addFilterAfter(myFilter(), OAuth2ClientContextFilter.class)
          .httpBasic().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/openid_connect_login"))
          .and()
          .authorizeRequests()
          .antMatchers("/","/index*").permitAll()
          .anyRequest().authenticated()
          ;
  
       // @formatter:on
      }
  }
  </code></pre>
  
  <p>So why can my controller not access the userdetails?</p>
  
  <p>EDIT: as requested, <code>OpenIdConnectFilter</code>:</p>
  
  <pre><code> package org.baeldung.security;
  
  import java.io.IOException;
  import java.net.URL;
  import java.security.interfaces.RSAPublicKey;
  import java.util.Date;
  import java.util.Map;
  
  import javax.servlet.ServletException;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  
  import org.springframework.beans.factory.annotation.Value;
  import org.springframework.security.authentication.AuthenticationManager;
  import org.springframework.security.authentication.BadCredentialsException;
  import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  import org.springframework.security.core.Authentication;
  import org.springframework.security.core.AuthenticationException;
  import org.springframework.security.jwt.Jwt;
  import org.springframework.security.jwt.JwtHelper;
  import org.springframework.security.jwt.crypto.sign.RsaVerifier;
  import org.springframework.security.oauth2.client.OAuth2RestOperations;
  import org.springframework.security.oauth2.client.OAuth2RestTemplate;
  import org.springframework.security.oauth2.common.OAuth2AccessToken;
  import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
  import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
  
  import com.auth0.jwk.Jwk;
  import com.auth0.jwk.JwkProvider;
  import com.auth0.jwk.UrlJwkProvider;
  import com.fasterxml.jackson.databind.ObjectMapper;
  
  public class OpenIdConnectFilter extends AbstractAuthenticationProcessingFilter {
      @Value("${oidc.clientId}")
      private String clientId;
  
      @Value("${oidc.issuer}")
      private String issuer;
  
      @Value("${oidc.jwkUrl}")
      private String jwkUrl;
  
      public OAuth2RestOperations restTemplate;
  
      public OpenIdConnectFilter(String defaultFilterProcessesUrl) {
          super(defaultFilterProcessesUrl);
          setAuthenticationManager(new NoopAuthenticationManager());
      }
  
      @Override
      public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
  
          OAuth2AccessToken accessToken;
          logger.info("ewd here: b " );
          try {
              accessToken = restTemplate.getAccessToken();
          } catch (final OAuth2Exception e) {
              throw new BadCredentialsException("Could not obtain access token", e);
          }
          try {
              logger.info("ewd access token: " + accessToken);
              final String idToken = accessToken.getAdditionalInformation().get("id_token").toString();
              String kid = JwtHelper.headers(idToken)
                  .get("kid");
              final Jwt tokenDecoded = JwtHelper.decodeAndVerify(idToken, verifier(kid));
              final Map&lt;String, String&gt; authInfo = new ObjectMapper().readValue(tokenDecoded.getClaims(), Map.class);
              verifyClaims(authInfo);
              final OpenIdConnectUserDetails user = new OpenIdConnectUserDetails(authInfo, accessToken);
              logger.info("ewd user token: " + tokenDecoded);
              return new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
          } catch (final Exception e) {
              throw new BadCredentialsException("Could not obtain user details from token", e);
          }
  
      }
  
      public void verifyClaims(Map claims) {
          int exp = (int) claims.get("exp");
          Date expireDate = new Date(exp * 1000L);
          Date now = new Date();
          if (expireDate.before(now) || !claims.get("iss").equals(issuer) || !claims.get("aud").equals(clientId)) {
              throw new RuntimeException("Invalid claims");
          }
      }
  
  
      private RsaVerifier verifier(String kid) throws Exception {
          JwkProvider provider = new UrlJwkProvider(new URL(jwkUrl));
          Jwk jwk = provider.get(kid);
          return new RsaVerifier((RSAPublicKey) jwk.getPublicKey());
      }
  
      public void setRestTemplate(OAuth2RestTemplate restTemplate2) {
          restTemplate = restTemplate2;
  
      }
  
      private static class NoopAuthenticationManager implements AuthenticationManager {
  
          @Override
          public Authentication authenticate(Authentication authentication) throws AuthenticationException {
              throw new UnsupportedOperationException("No authentication should be done with this AuthenticationManager");
          }
  
      }
  }
  </code></pre>