3

I am having my oauth client resttemplate configuration like following. I get the following exception. I researched and there are lots of areas which same exception but not able to resolve this. There is also existing issue with same exception here but there is no resolution. I am using

There is no client authentication. Try adding an appropriate authentication filter.

@Bean
    @Qualifier("clientOnlyFullAcessDetails")
    public OAuth2ProtectedResourceDetails clientOnlyFullAcessDetails() {
        ClientCredentialsResourceDetails resource = new ClientCredentialsResourceDetails();
        resource.setAccessTokenUri(tokenUrl);
        resource.setClientId(clientId);
        resource.setClientSecret(clientSecret);
        resource.setScope(Collections.singletonList(ClientScope.server.name()));
        resource.setClientAuthenticationScheme(AuthenticationScheme.header);
        resource.setAuthenticationScheme(AuthenticationScheme.header);
        return resource;
    }

    @Bean
    @Qualifier("clientOnlyRestTemplate")
    public OAuth2RestTemplate clientOnlyRestTemplate() {
        OAuth2RestTemplate template = new OAuth2RestTemplate(clientOnlyFullAcessDetails(),
                new DefaultOAuth2ClientContext(new DefaultAccessTokenRequest()));
        template.setAccessTokenProvider(clientAccessTokenProvider());
        return template;
    }

    @Bean
    public AccessTokenProvider clientAccessTokenProvider() {
        ClientCredentialsAccessTokenProvider accessTokenProvider = new ClientCredentialsAccessTokenProvider();
        accessTokenProvider.setRequestFactory(new SimpleClientHttpRequestFactory());
        return accessTokenProvider;
    }

My authorization server code is

private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        final TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer(), accessTokenConverter()));
        // @formatter:off
        endpoints
             .tokenStore(tokenStore())
             .tokenEnhancer(tokenEnhancerChain);
 //            .authenticationManager(authenticationManager);
        // @formatter:on
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        jwtAccessTokenConverter.setSigningKey("123");
//      KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource(keystoreFileUri),
//              keystorePassword.toCharArray());
//      jwtAccessTokenConverter.setKeyPair(keyStoreKeyFactory.getKeyPair(keystoreAlias));
        return jwtAccessTokenConverter;
    }

    @Bean
    @Primary
    public DefaultTokenServices tokenServices() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        defaultTokenServices.setSupportRefreshToken(true);
        return defaultTokenServices;
    }

    @Bean
    public TokenEnhancer tokenEnhancer() {
        return new CustomTokenEnhancer();
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(datasource).passwordEncoder(passwordEncoder);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        // @formatter:off
        security
         .tokenKeyAccess("permitAll()")
         .checkTokenAccess("isAuthenticated()")
         .passwordEncoder(passwordEncoder);
        // @formatter:on
    }

web security for auth server

@Override
    public void configure(HttpSecurity http) throws Exception {
        // @formatter:off

        HeadersConfigurer<HttpSecurity> headerSecutiy = http
          .headers()
          .frameOptions()
          .disable();

        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry urlSecurity = headerSecutiy.and()
          .csrf()
          .disable()
          .authorizeRequests()
          .antMatchers("/oauth/token").permitAll();

        urlSecurity
          .anyRequest()
          .authenticated();

        urlSecurity.
         and()
          .sessionManagement()
          .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
          .exceptionHandling()
          .accessDeniedHandler(new OAuth2AccessDeniedHandler());
        // @formatter:on
    }
Saurabh Kumar
  • 16,353
  • 49
  • 133
  • 212

1 Answers1

0

I experienced this error message within test with setup relying on MockMvc. The issue was that MockMvc isnt aware of the spring security filter chain which needs to be set up for the MockMvc


@SpringBootTest
@ActiveProfiles("test")
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = SecurityApplication.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class SecurityTest {

    private MockMvc mvc;

    @Autowired
    private WebApplicationContext wac;

    @BeforeAll
    public void before() {
        mvc = MockMvcBuilders
            .webAppContextSetup(wac)
            .alwaysDo(doPrint())
            .apply(SecurityMockMvcConfigurers.springSecurity())  // Wire app Security Filter chain to inject then Pricipal
            .build();
    }

    @WithMockUser(username = "user", password = "secret", roles = "USER")
    public void currentLoggedUser() throws Exception {
        mvc.perform(MockMvcRequestBuilders
            .get("/me")
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
    }

}