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

Posted

技术标签:

【中文标题】没有客户端身份验证。尝试添加适当的身份验证过滤器异常 spring oauth2【英文标题】:There is no client authentication. Try adding an appropriate authentication filter exception spring oauth2 【发布时间】:2019-04-09 09:08:55 【问题描述】:

我的 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】:

我在测试中遇到此错误消息,安装程序依赖于 模拟Mvc。问题是 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())
    



【讨论】:

以上是关于没有客户端身份验证。尝试添加适当的身份验证过滤器异常 spring oauth2的主要内容,如果未能解决你的问题,请参考以下文章

Spring/OAuth2 错误 - InsufficientAuthenticationException,没有客户端身份验证。尝试添加适当的身份验证过滤器

如果身份验证失败,则关闭 HTTP 连接

没有用户模型的 Laravel JWT 身份验证

在 JAVA 的 elasticsearch 高级客户端中添加身份验证

启用证书身份验证时获取 401.2

为 web 应用程序使用的 python REST API 选择适当的身份验证类