spring-boot - KeyCloak Spring Boot - 在验证成功时添加自定义代码
问题描述
我在本指南中使用 KeyCloak 与 Spring Boot 的集成。我的安全配置如下:
class KeycloakSecurityConfiguration extends KeycloakWebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests().antMatchers("/**").authenticated()
.anyRequest().permitAll();
}
}
我想onAuthenticationSuccess
在 KeyCloak 将我重定向到实际资源之前添加一些自定义代码。我尝试使用AuthenticationSuccessHandler
and do实现一个自定义类formLogin().successHandler(...)
。这没有用。我怎样才能得到这个工作?
解决方案
如果您仍然喜欢使用 Spring Boot KeyCloak,那么这样的方法将起作用。
public class KeyCloakAuthSuccessHandler extends KeycloakAuthenticationSuccessHandler {
public KeyCloakAuthSuccessHandler(AuthenticationSuccessHandler fallback) {
super(fallback);
}
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
if (authentication.getPrincipal() instanceof KeycloakPrincipal) {
AccessToken token = ((KeycloakPrincipal<?>) authentication.getPrincipal()).getKeycloakSecurityContext().getToken();
}
super.onAuthenticationSuccess(request, response, authentication);
}
}
在您的安全配置或扩展的类似文件中KeyCloakWebSecurityConfigurerAdapter
执行以下操作:
@Bean
@Override
protected KeycloakAuthenticationProcessingFilter keycloakAuthenticationProcessingFilter() throws Exception {
KeycloakAuthenticationProcessingFilter filter = new KeycloakAuthenticationProcessingFilter(authenticationManagerBean());
filter.setSessionAuthenticationStrategy(sessionAuthenticationStrategy());
filter.setAuthenticationSuccessHandler(successHandler());
return filter;
}
@NotNull
@Bean
public KeyCloakAuthSuccessHandler successHandler() {
return new KeyCloakAuthSuccessHandler(new SavedRequestAwareAuthenticationSuccessHandler());
}
推荐阅读
- nginx - Nginx image_filter resize 丢失元数据
- tfs - TFS 从 Main 创建分支 - 选定的变更集
- macos - VS 2017 + Unity + Mac OS high sierra (10.13.4) 符号链接和别名不起作用
- javascript - 在 Gatsby 的 404 页面上显示 URL
- jquery - JQuery DataTable Export Excel 无法将内置样式应用于空单元格
- sql - SQL 中的分组和排序
- html - HTML - div 中的第一个文本不会被下推
- android - 运算符 '*' 不能应用于 'android.widget.RadioButton', 'int'
- amazon-web-services - AWS 实例随机超时
- c# - 使用条件唯一约束保存实体时出现循环依赖错误