带有密钥斗篷设置的Spring安全性(HttpSecurity)



我有以下设置:

  1. 一个基于角度的前端,它与
  2. 基于java的后端,反过来进行通信
  3. 在组织中提供第三方服务

前端/后端访问由oauth2保护,oauth2查询密钥斗篷服务器。这个密钥斗篷服务器对我的应用程序和我的后端正在访问的第三方服务的用户进行身份验证。获取第三方服务的访问令牌的代码如下(事实上,这是出现问题的代码:当调用template.getAccessToken()时,另请参阅下文(:

private void setAccessToken(HttpRequest request) {
HttpHeaders headers = new HttpHeaders();
OAuth2RestTemplate template = new OAuth2RestTemplate(resourceOwnerDetails());
OAuth2AccessToken accessToken = template.getAccessToken();
headers.setAuthorization("Bearer " + accessToken);
request.setHeaders(headers);
}

安全配置如下:

@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.requiresChannel()
.anyRequest()
.requiresSecure()
.and()
.cors()
.and()
.csrf()
.disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.ALWAYS)
.sessionAuthenticationStrategy(sessionAuthenticationStrategy())
.and()
.authorizeRequests()
.antMatchers("/accessdenied", "/accessdenied/**", "/style/*")
.permitAll()
.antMatchers("/")
.hasAnyRole(allowedRoles)
.anyRequest()
.hasAnyRole(allowedRoles)
.and()
.exceptionHandling()
.accessDeniedPage("/accessdenied");

当需要对前端/GUI访问和后端查询的第三方服务进行身份验证时,这很好。

我的问题如下:在某些条件下(测试人员(,我希望用户不必通过前端/GUI访问的身份验证。但是,为了访问第三方服务,始终需要进行身份验证。

要在没有身份验证的情况下访问前端,我可以做一个简单的配置,例如:

http.authorizeRequests().antMatchers("/**").permitAll().and().csrf().disable();

这样,我就可以在不经过身份验证的情况下访问GUI(这正是我想要的(,但当涉及到通过template.getAccessToken()获得oauth2访问令牌时(见上文(,会抛出一个异常

org.springframework.security.authentication.InsufficientAuthenticationException: Authentication is required to obtain an access token (anonymous not allowed)

所以,我想我要找的是合适的安全配置。如何配置spring安全性,使其不验证GUI/前端访问,但仍能获得第三方服务的访问令牌?任何指向正确方向的指针都将不胜感激。

pom.xml 中的

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>

在您的配置类中

import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.jwk.JwkTokenStore;
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Bean
public TokenStore tokenStore() {
return new JwkTokenStore("http://localhost:8080/auth/realms/master/protocol/openid-connect/certs");
}
}
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.jwk.JwkTokenStore;
@KeycloakConfiguration
@Configuration
@EnableWebSecurity
@ComponentScan(
basePackageClasses = KeycloakSecurityComponents.class
)
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
@Bean
public TokenStore tokenStore() {
return new JwkTokenStore("http://localhost:8080/auth/realms/master/protocol/openid-connect/certs");
}
}

最新更新