问题描述
我需要在 Spring Boot 应用程序上公开多个端点。 我使用 oauth2 来实现使用令牌的安全性,但需要几个端点是公共的并且不需要授权令牌。
 
    我已经尝试过(从我发现的几篇文章中)实现了这样的WebSecurityConfigurerAdapter配置类:
@Configuration
@EnableWebSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity httpSecurity) {
    httpSecurity
            .antMatcher("/**")
            .authorizeRequests()
            .antMatchers('/actuator/jolokia', '/graphiql', '/voyager')
            .permitAll()
            .anyRequest()
            .authenticated()
}
,但无济于事,端点不断要求访问令牌
    我用于启用 oauth 的pom.xml依赖项是这样的: <dependency> <groupId>org.springframework.security.oauth.boot</groupId> <artifactId>spring-security-oauth2-autoconfigure</artifactId> <version>${spring-security-oauth2.version}</version> </dependency>
此外,这是 oauth 授权服务器的配置类:
@Component
@EnableResourceServer
@EnableAuthorizationServer
class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Value('${application.oauth.clientId}')
String clientId
@Value('${application.oauth.secret}')
String clientSecret
@Value('${application.oauth.accessTokenExpirationSeconds}')
Integer accessTokenExpirationSeconds
@Value('${application.jwt.key}')
String jwtKey
AuthenticationManager authenticationManager
AuthorizationServerConfiguration(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        this.authenticationManager =     authenticationConfiguration.getAuthenticationManager()
}
@Override
void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder()
    String encoded = passwordEncoder.encode(clientSecret)
    clients.inMemory()
            .withClient(clientId)
            .secret(encoded)
            .authorizedGrantTypes("client_credentials")
            .scopes("all")
            .accessTokenValiditySeconds(accessTokenExpirationSeconds)
}
@Override
void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    endpoints.authenticationManager(authenticationManager)
            .accessTokenConverter(accessTokenConverter())
}
@Bean
JwtAccessTokenConverter accessTokenConverter() {
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter()
    converter.setSigningKey(jwtKey)
    converter.setVerifierKey(jwtKey)
    converter.afterPropertiesSet()
    converter
}
@Bean
TokenStore tokenStore() {
    new JwtTokenStore(accessTokenConverter())
}
1楼
在您的 SecurityConfig 中,您需要使用 .and() 将单独的语句连接在一起,否则它们将在单个语句中连接在一起。
尝试这个:
httpSecurity
  .antMatcher("/**")
  .authorizeRequests()
  .and()
  .authorizeRequests().antMatchers('/actuator/jolokia', '/graphiql', '/voyager').permitAll()
  .and()
  .authorizeRequests().anyRequest().authenticated();