使用自定义登录页面将Keycloak与Spring Boot集成(不使用Keycloak的默认登录页面即可登录)

时间:2019-01-16 10:07:04

标签: spring-boot spring-security keycloak

  

我要实现的目标:   用户可以使用我们项目的登录页面(在项目内)登录,而无需重定向到keycloak的默认登录页面。我已经用Keycloak配置了spring security,它可以正常工作但是用户通过keycloak的默认登录页面登录

     

我的问题:如何实现此功能,我将使用REST API从Keycloak获取令牌

   curl \
  -d "client_id=id-client" \
  -d "username=username" \
  -d "password=psw" \
  -d "grant_type=password" \
  -d "client_secret=secret" \
  "http://localhost:8080/auth/realms/myRealmName/protocol/openid-connect/token"
  

并授予访问我的Spring项目的权限(无论Spring安全性如何)

据我了解,我可以在前端使用jquery登录并获取令牌,最终传递给Spring Security或其他任何东西

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

我们已经找到了解决此问题的好方法,我将逐步解释: 首先,如果要使用自定义登录页面,则有两个选择: 1.修改现有的密钥库,例如登录/注册/密码更新,可通过/ keycloak / themes / *目录找到 2.这可能有点棘手-可以通过在项目中修改Spring Security的AuthenticationProvider来实现。

override fun configure(http: HttpSecurity?) {
        http
            ?.authorizeRequests()
            ?.antMatchers("/**")?.authenticated()
            ?.and()
            ?.authenticationProvider(myAuthenticationProvider)
            ?.formLogin()
            ?.loginPage("/login")
            ?.successHandler { request, response, authentication ->  redirectStrategy.sendRedirect(request, response, "/main")}
            ?.permitAll()
            ?.usernameParameter("username") //the username parameter in the queryString, default is 'username'
            ?.passwordParameter("password") //the password parameter in the queryString, default is 'password'
            ?.and()
            ?.logout()
            ?.logoutUrl("/logout") //the URL on which the clients should post if they want to logout
            ?.invalidateHttpSession(true)
            ?.and()
            ?.exceptionHandling()
    }
  

MyAuthenticationProvider,您应该覆盖此春季安全性类

     

我在上述问题中又问了一件事,如果我使用rest api来访问spring项目,在这种情况下,您应该实现KeycloakWebSecurityConfigurerAdapter而不是WebSecurityConfigurerAdapter