我正在尝试设置 Keycloak 和 spring 应用程序身份验证。我需要当用户尝试访问受保护的资源时,他会被重定向到 Keycloak 身份验证页面,并且在身份验证成功后,他会被重定向回来,但标头中带有不记名令牌。 目前,Spring Security 配置如下所示:
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
private final String[] anonymousList = {
"api/demo/home"
};
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable);
http.authorizeHttpRequests(
auth -> auth.requestMatchers(anonymousList)
.permitAll()
.anyRequest()
.authenticated()
);
http.oauth2Login(Customizer.withDefaults());
return http.build();
}
}
application.yml
spring:
security:
oauth2:
client:
provider:
keycloak:
issuer-uri: ${ISSUER_URI}
registration:
keycloak:
client-id: ${CLIENT_ID}
client-secret: ${CLIENT_SECRET}
authorization-grant-type: authorization_code
scope: openid
在这种情况下,登录时,会在设置的 cookie 中放置一个序列化 ID 令牌。使用spring后端作为oauth2客户端授权成功后是否可以在请求头中添加Bearer token?
身份验证成功后,他会被重定向回来,但标头中带有不记名令牌
这很可能是错误的期望:访问令牌不应发送到浏览器和移动应用程序。
您正在使用
oauth2Login
,这意味着 对 Spring 应用程序的请求是通过会话 cookie 进行授权的,而不是 Bearer
令牌。这也意味着您的应用程序容易受到 CSRF 攻击,并且您确实应该启用 CSRF 保护。
如果您的前端是单页(Angular、Vue、React...)或移动应用程序,您可以使用 spring-cloud-gateway 作为 OAuth2 BFF:
oauth2Login
从授权服务器获取令牌并将其保存在会话中TokenRelay
过滤器将会话 cookie 替换为 Bearer 标头(使用匹配会话中的令牌进行设置)我在 Baeldung 上写了关于 BFF 模式的教程。