目前我在端口 8082 和 8083 上有 2 个 Spring Boot 应用程序。
在端口 8082 上运行的应用程序是 Zuul 网关。我想使用此应用程序来防止无法访问可在 8083 上找到的资源的用户通过发送错误的令牌来减慢该应用程序的速度。
我使用 Keycloak 作为开放 id 提供程序(在端口 8180 上运行)。
我让它与 keycloak 适配器和一些 java 配置类一起工作,但我想知道我是否可以让它更容易,只使用 Zuul?
我有这些 application.properties 和 application.yml:
zuul:
sensitiveHeaders: Cookie,Set-Cookie
routes:
resource:
path: /resource/**
url: http://localhost:8083
keycloak.auth-server-url = http://localhost:8180/auth
keycloak.resource = my-service
keycloak.credentials.secret = my-client-secret
keycloak.realm = dev
keycloak.ssl-required = none
keycloak.use-resource-role-mappings = true
keycloak.bearer-only = true
我的配置类:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true, securedEnabled = true)
@RequiredArgsConstructor
public class KeycloakSecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http
.headers()
.frameOptions()
.disable()
.and()
.csrf()
.disable()
.authorizeRequests()
.antMatchers("/**").authenticated()
.and()
.sessionManagement(cust -> cust.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {
KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
auth.authenticationProvider(keycloakAuthenticationProvider);
}
@Bean
@Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
}
@Bean
public KeycloakConfigResolver keycloakConfigResolver() {
return new KeycloakSpringBootConfigResolver();
}
}
我的主要课程:
@SpringBootApplication
@EnableZuulProxy
public class ZuulApplication {
public static void main(String[] args) {
SpringApplication.run(ZuulApplication.class, args);
}
}
效果很好...如果我在 Postman 中向 http://localhost:8082/resource/hello
发送一个请求,其中 Authorization
标头包含 Bearer {access-token}
,它会在端口 8083 上代理到我的应用程序,然后我得到按预期返回消息 Hello World!
。但我想知道不使用 keycloak 适配器是否有更简单的设置?如果可能,只能通过配置 Zuul 吗?如果没有,在更改某些 URI/属性后,我如何制作一个适用于大多数 openid 提供程序的“通用”实现? (如果我想使用另一个 openid 提供程序而不是 keycloak,这可能很有用...)
提前致谢。