授权失败时带有Keycloak适配器的Springboot重定向到登录页面
Springboot with Keycloak adapter redirecting to login page when authorization fail
在历史上,我能够使用 keycloak 适配器创建 API 并根据用户的角色保护所有端点。
今天(一年后),我正在尝试做同样的事情(几乎是从以前的解决方案中复制粘贴)但没有成功..
我创建了一个超级简单的 API 和 spring 启动。定义的 SecurityConfig 如:
@Autowired
public void configureGlobal(
AuthenticationManagerBuilder auth) throws Exception {
KeycloakAuthenticationProvider keycloakAuthenticationProvider
= keycloakAuthenticationProvider();
keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(
new SimpleAuthorityMapper());
auth.authenticationProvider(keycloakAuthenticationProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests()
.anyRequest()
.permitAll();
http.csrf().disable();
}
还有 1 个端点
@GetMapping("/test")
@RolesAllowed("admin")
public Test testEndpoint() {
return new Test();
}
但是每当我尝试在 /test 上发送 GET(未经授权 header)时,我都会收到对 OpenID 配置中指定的 {{authorization_url}} 的重定向响应(keycloak-spring-boot-starter成功设法从 Keycloak 本身下载此配置)。据我所知,Keycloak 要我重定向到登录页面并自己登录。
这有点新鲜。以前,这并没有发生,springboot 只是简单地返回 401 左右...
是否有一个选项,我可以在哪些设置中更改此行为,使其不响应重定向?相反,只是抛出一个异常?
将 bearer-only 选项配置为 true - 它将启用“API”模式,因此它将 return 401 Unauthorized
http 响应。您现在在“网络应用程序”模式下使用它,将用户重定向到 IDP 登录(这对 API 调用来说不是好的行为)。
在历史上,我能够使用 keycloak 适配器创建 API 并根据用户的角色保护所有端点。
今天(一年后),我正在尝试做同样的事情(几乎是从以前的解决方案中复制粘贴)但没有成功..
我创建了一个超级简单的 API 和 spring 启动。定义的 SecurityConfig 如:
@Autowired
public void configureGlobal(
AuthenticationManagerBuilder auth) throws Exception {
KeycloakAuthenticationProvider keycloakAuthenticationProvider
= keycloakAuthenticationProvider();
keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(
new SimpleAuthorityMapper());
auth.authenticationProvider(keycloakAuthenticationProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests()
.anyRequest()
.permitAll();
http.csrf().disable();
}
还有 1 个端点
@GetMapping("/test")
@RolesAllowed("admin")
public Test testEndpoint() {
return new Test();
}
但是每当我尝试在 /test 上发送 GET(未经授权 header)时,我都会收到对 OpenID 配置中指定的 {{authorization_url}} 的重定向响应(keycloak-spring-boot-starter成功设法从 Keycloak 本身下载此配置)。据我所知,Keycloak 要我重定向到登录页面并自己登录。
这有点新鲜。以前,这并没有发生,springboot 只是简单地返回 401 左右...
是否有一个选项,我可以在哪些设置中更改此行为,使其不响应重定向?相反,只是抛出一个异常?
将 bearer-only 选项配置为 true - 它将启用“API”模式,因此它将 return 401 Unauthorized
http 响应。您现在在“网络应用程序”模式下使用它,将用户重定向到 IDP 登录(这对 API 调用来说不是好的行为)。