【发布时间】:2021-01-09 12:18:12
【问题描述】:
我在 this documentation 之后使用 Keycloak 11.0.2 和 Spring Security 保护了我的 Spring Boot 应用程序。
我在application.properties中使用了基本的Keycloak配置:
keycloak.auth-server-url=http://localhost:8085/auth
keycloak.realm=cirta
keycloak.resource=cirta-api
keycloak.public-client=false
我有一个单独的前端 Angular 应用程序,它在 Keylocak 中配置为不同的客户端;但与 Spring Boot 应用程序处于同一领域。从 Angular 应用程序中,我在 HTTP 标头中发送 Keycloak 提供的令牌:
'Authorization' : 'Bearer ' + this.securityService.kc.token
当我访问调用 GET API 的 Angular 页面时,我收到 blocked by CORS policy 错误:
Access to XMLHttpRequest at 'http://localhost:8080/api/modePaiements' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
所以我尝试将keycloak.cors=true 属性添加到application.properties。添加该属性后,GET 调用正在运行。但是现在当我调用 POST/PUT API 时,我收到了 Failed to load resource: the server responded with a status of 403 () 错误。
KeycloakWebSecurityConfigurerAdapter:
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests().antMatchers("/api/*").hasRole("app-manager").anyRequest().permitAll();
}
Spring 示例应用程序: https://github.com/bilaldekar/kc
Angular 示例应用程序: https://github.com/bilaldekar/kc-ang
请求标头:
【问题讨论】:
-
评论不用于扩展讨论;这个对话是moved to chat。
-
this.securityService.kc.token解码后的有效载荷是什么样的?有app-manager角色吗? -
我在问题中添加了令牌,是的,我创建了一个角色 app-manager。
-
@deduper 你能给出解决 401/403 的配置吗,我会用前端调用测试它,看看它是否有效
-
我发现后端 api 应该仅配置为承载,而不是公共客户端,以便通过前端发送的令牌提供对 api 的访问,但这并没有解决问题
标签: angular spring-boot spring-security keycloak http-status-code-403