没有客户端身份验证。尝试添加适当的身份验证过滤器异常spring oauth2

时间:2018-11-06 00:01:15

标签: spring-boot spring-security spring-security-oauth2 spring-security-rest

我正在执行如下的oauth client resttemplate配置。我得到以下异常。我研究了很多领域,但有相同的例外,但无法解决。还存在具有相同异常here的问题,但是没有解决方案。我正在使用

  

没有客户端身份验证。尝试添加适当的   身份验证过滤器。

@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;
    }

我的授权服务器代码是

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
    }

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
    }

1 个答案:

答案 0 :(得分:0)

我在测试过程中遇到此错误消息,并且安装程序依赖 MockMvc。问题是MockMvc不了解需要为MockMvc设置的spring安全过滤器链。


@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())
    }

}