gpt4 book ai didi

java - 如何使用 spring boot 和 oauth2 公开端点

转载 作者:行者123 更新时间:2023-11-30 05:46:44 30 4
gpt4 key购买 nike

我需要在我的 Spring Boot 应用程序上公开多个端点。我使用 oauth2 使用 token 实现安全性,但需要几个端点公开并且不需要授权 token 。

我尝试过(从我发现的几篇文章中)实现 WebSecurityConfigurerAdapter配置类如下:

@Configuration
@EnableWebSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity httpSecurity) {
httpSecurity
.antMatcher("/**")
.authorizeRequests()
.antMatchers('/actuator/jolokia', '/graphiql', '/voyager')
.permitAll()
.anyRequest()
.authenticated()
}

},但无济于事,端点不断要求访问 token

pom.xml我用于启用 oauth 的依赖项是这样的: <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();

关于java - 如何使用 spring boot 和 oauth2 公开端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54700070/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com