我需要在Spring启动应用程序中公开几个端点。我使用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())
}
在SecurityConfig中,您需要将单独的语句与.and()一起加入,否则它们将在一个语句中连接在一起。
试试这个:
httpSecurity
.antMatcher("/**")
.authorizeRequests()
.and()
.authorizeRequests().antMatchers('/actuator/jolokia', '/graphiql', '/voyager').permitAll()
.and()
.authorizeRequests().anyRequest().authenticated();