结合springboot和keycloak做登陆验证

前言

登陆是一个项目的基础,几乎任何项目都需要包括登陆模块,网上大部分登陆都是使用的shrio,个人感觉这种东西很老,而且不好用,偶然之前发现了一个叫keycloak的sso开源项目, 感觉挺不错的,这篇文章主要讲解如何使用springboot和keycloak进行结合。

版本

  1. springboot: 1.4.3.RELEASE 版本
  2. keycloak: 2.5.1.Final 版本
  3. vue: 2.1.0 版本

项目搭建

  1. 首先搭建keycloak的服务 (略)
  2. 编写前端代码(用vue2写的简单的一个spa,略)
  3. 编写springboot的服务(略)
  4. 加入核心依赖
        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-tomcat8-adapter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-spring-security-adapter</artifactId>
        </dependency>
  1. 在springboot的配置文件中加入
keycloak:
       configurationFile: "classpath:keycloak.json"
  1. 在resources的目录下加入 keycloak.json 配置文件
{
  "realm": "family",
  "bearer-only": true,
  "auth-server-url": "http://localhost:8080/auth",
  "ssl-required": "external",
  "resource": "family-app",
  "enable-cors": true
}
  1. 配置springmvc的跨域filter
@Configuration
public class CorsFilterConfig implements Filter {

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {}

  @Override
  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
      FilterChain filterChain) throws IOException, ServletException {
    HttpServletResponse res = (HttpServletResponse) servletResponse;
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
    res.setHeader("Access-Control-Max-Age", "1728000");
    res.setHeader("Access-Control-Allow-Headers",
        "Authorization, Content-Type, Accept, x-requested-with, Cache-Control");
    filterChain.doFilter(servletRequest, res);
  }

  @Override
  public void destroy() {}
}
  1. 配置keycloak和spring security结合的配置文件
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
public class KeycloakSecurityConfig extends KeycloakWebSecurityConfigurerAdapter {

  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(keycloakAuthenticationProvider());
  }

  @Bean
  @Override
  protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
    return new NullAuthenticatedSessionStrategy();
  }

  @Bean
  public FilterRegistrationBean keycloakAuthenticationProcessingFilterRegistrationBean(
      KeycloakAuthenticationProcessingFilter filter) {
    FilterRegistrationBean registrationBean = new FilterRegistrationBean(filter);
    registrationBean.setEnabled(false);
    return registrationBean;
  }

  @Bean
  public FilterRegistrationBean keycloakPreAuthActionsFilterRegistrationBean(
      KeycloakPreAuthActionsFilter filter) {
    FilterRegistrationBean registrationBean = new FilterRegistrationBean(filter);
    registrationBean.setEnabled(false);
    return registrationBean;
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    super.configure(http);
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .sessionAuthenticationStrategy(sessionAuthenticationStrategy()).and()
        .addFilterBefore(keycloakPreAuthActionsFilter(), LogoutFilter.class)
        .addFilterBefore(keycloakAuthenticationProcessingFilter(), X509AuthenticationFilter.class)
        .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint()).and()
        .authorizeRequests()
        .requestMatchers(CorsUtils::isCorsRequest).permitAll()
//        .antMatchers("/family/*").hasAnyAuthority("user").antMatchers("/admin/*").hasRole("ADMIN")
        .antMatchers("/**").authenticated()
        .anyRequest().permitAll();
  }
}
  1. 对应的接口上增加可以执行的用户角色
@RequestMapping(value = "/all", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
  @ResponseBody
  @PreAuthorize("hasAnyAuthority('user')")
  public List<Family> queryAllFamilyInfo() {
    return familyInfoService.queryAllFamilyInfo();
  }

遇到的坑

  1. 对应keycloak的用户权限需要使用 hasAnyAuthority而不是 hasAnyRole,并且需要在KeycloakSecurityConfig类中加入@EnableGlobalMethodSecurity(prePostEnabled = true) 注解
  2. keycloak-spring-security-adapterspring-boot-adpater 两个依赖不能同时使用
  3. cors的跨域的配置,需要CorsFilterConfig的filter类配合KeycloakSecurityConfig类中的 requestMatchers(CorsUtils::isCorsRequest).permitAll()一起使用

完整的项目地址(包括了简单的前端和后端代码,不会写前端,前端代码比较垃圾。。 需要完善 ):

https://github.com/dragontree101/springboot-keycloak-demo

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,188评论 19 139
  • 本文包括:1、Filter简介2、Filter是如何实现拦截的?3、Filter开发入门4、Filter的生命周期...
    廖少少阅读 12,093评论 3 56
  • 工作到现在快要1年半了,一直没有时间自己从头搭建个框架,这个周末实在是无聊,真的不想打lol了,(黑色玫瑰开黑的喊...
    MacSam阅读 11,909评论 7 20
  • 关于 springmvc 3.x 版本对ajax跨域请求访问 ajax 请求后,浏览器出现跨域的问题那么在当前环境...
    山水风情阅读 3,437评论 0 0
  • 文/A 幸运点 韶华减岁夏风收,叶宿江东误水流。 漫卷寒云行日月,轻撩细浪数春秋。 飞来几度红尘雨,没入千年白鹭洲...
    A幸运点阅读 3,414评论 5 13

友情链接更多精彩内容