【发布时间】:2019-01-14 11:46:00
【问题描述】:
我需要将身份验证添加到我的 Spring Boot (MVC) 应用程序中。身份验证提供者是通过 OpenID 的 keycloak。隐式和授权代码授权都被禁用,所以我被资源所有者凭据授权所困扰。我想要实现的是未授权用户的基本身份验证提示。以这种方式检索的凭据应该用于从 keycloak 获取令牌和用户信息,以供 Spring Security 进一步使用。应在每个请求上检查令牌。
我发现的大多数示例都使用org.keycloak:keycloak-spring-boot-starter 的重定向功能。虽然我找到了enable-basic-auth here,但它对我不起作用。我知道我必须使用 keycloak.bearer-only=true 来关闭重定向,但它可以正常工作,而不是重定向它为未经授权的用户返回 401。
我的安全配置:
@Configuration
@EnableWebSecurity
@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
@Bean
public KeycloakSpringBootConfigResolver KeycloakConfigResolver() {
return new KeycloakSpringBootConfigResolver();
}
@Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().permitAll();
}
}
我的 keycloak 属性(我不使用占位符,只是为了安全起见):
keycloak.auth-server-url=https://${keycloak.host}/auth/
keycloak.realm=master
keycloak.resource=${client.name}
keycloak.enable-basic-auth=true
keycloak.credentials.secret=${client.secret}
很抱歉提出一般性问题。我主要使用 jdbcAuthentication,这是我第一次使用身份管理软件。
【问题讨论】:
-
请注意,在您引用的那个文档中,它说“如果启用此选项,则还必须提供秘密。”这需要在客户端适配器的配置和领域中进行配置。见github.com/keycloak/keycloak/blob/master/examples/basic-auth/…这是来自官方keycloak基本认证示例
-
@RyanDawson 感谢您的回复!是的,我已打开所有这些选项:
keycloak.credentials.secret=66666a66-66a6-6a66-666a-6a6a66aa666和Direct Access Grants Enabled已打开。 -
您看到的失败行为是什么?我不清楚你所说的“不工作”是什么意思
-
@RyanDawson 我已经能够通过删除
spring-boot-starter-security和SecurityConfig.java来实现使用curl 的基本身份验证,但是在浏览器中而不是获得基本身份验证提示时,我得到了重定向。使用spring-boot-starter-security和SecurityConfig基本身份验证即使使用 curl (HTTP/1.1 302Location: http://localhost:8080/sso/login) 也不起作用。 localhost:8080 是我的申请地址。 -
更新:需要自定义 authenticationEntryPoint 和
keycloak.bearer-only=true。401响应的标头错误。应该是WWW-Authenticate: Basic realm="Restricted Content"我稍后会发布代码
标签: java spring-boot spring-security keycloak