我需要将身份验证添加到我的 Spring Boot (MVC) 应用程序中。身份验证提供者是通过 OpenID 的 keycloak。隐式授予和授权代码授予均被禁用,因此我只能使用资源所有者凭据授予。我想要实现的是针对未经授权的用户的基本身份验证提示。以这种方式检索到的凭证应用于从 keycloak 获取令牌和用户信息,以便 spring security 进一步使用。应在每个请求时检查令牌。
我发现的大多数示例都使用org.keycloak:keycloak-spring-boot-starter. enable-basic-auth 虽然我在这里找到了,但它对我不起作用。我知道我必须使用它keycloak.bearer-only=true来关闭重定向,但它可以正常工作,因此它不会为未经授权的用户返回 401,而是返回 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();
}
}
Run Code Online (Sandbox Code Playgroud)
我的 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}
Run Code Online (Sandbox Code Playgroud)
很抱歉问这个一般性问题。我主要使用 jdbcAuthentication,这是我第一次使用身份管理软件。