mysql - 如何获取Keycloak访问 token 并将其存储在数据库中以供Spring Boot使用?

标签 mysql spring-boot access-token keycloak

我想首先获取访问 token 并将登录期间由keycloak生成的访问 token 存储在我的数据库中。我正在使用 Spring Boot 。

这是我尝试获取访问 token 的代码..但结果是什么都没有....有更好的解决方案吗? ..

@RequestMapping(value = "/login", method = RequestMethod.GET)

public String getCustomers()
 {
HttpServletRequest request =((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes())
                .getRequest();
        KeycloakAuthenticationToken token = (KeycloakAuthenticationToken) request.getUserPrincipal();
        KeycloakPrincipal principal = (KeycloakPrincipal) token.getPrincipal();
        KeycloakSecurityContext session = principal.getKeycloakSecurityContext();
        AccessToken accessToken = session.getToken();
        String a = principal.getName();
        String username = accessToken.getPreferredUsername();
        String realmName = accessToken.getIssuer();
        AccessToken.Access realmAccess = accessToken.getRealmAccess();
        String s = session.getToken().toString();
        System.out.println(s);
        return realmName;
..  }

我希望获得keycloak生成的访问 token 并将其存储在数据库中。

@KeycloakConfiguration class SecurityConfig extends
  KeycloakWebSecurityConfigurerAdapter {
 /**
     * Registers the KeycloakAuthenticationProvider with the authentication manager.
     */


  @Autowired public void configureGlobal(AuthenticationManagerBuilder auth)
  throws Exception { KeycloakAuthenticationProvider
  keycloakAuthenticationProvider=keycloakAuthenticationProvider();
  keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new
  SimpleAuthorityMapper());
  auth.authenticationProvider(keycloakAuthenticationProvider); }

 /**
     * Defines the session authentication strategy.
     */
          @Bean

          @Override protected SessionAuthenticationStrategy
          sessionAuthenticationStrategy() { return new
          RegisterSessionAuthenticationStrategy(new SessionRegistryImpl()); }

          @Bean public KeycloakConfigResolver keycloakConfigResolver() { return new
          KeycloakSpringBootConfigResolver(); }

          @Override protected void configure(HttpSecurity http) throws Exception {
          super.configure(http); http .authorizeRequests()
          .antMatchers("/login*").hasRole("springrole") .anyRequest().permitAll(); } }
this is my keycloak configuration..

最佳答案

你需要登录到keycloak,我看到你只需调用自定义“/login”并期望keycloak主体。

关于mysql - 如何获取Keycloak访问 token 并将其存储在数据库中以供Spring Boot使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58285994/

相关文章:

c# - 从 Powershell 获取 Azure Active Directory 访问 token

MySQL:@variable 与变量。有什么不同? (第2部分)

Mysql 随机选择给出意想不到的结果

java - 如何从另一个测试中调用测试?

spring - Rest 模板中带有 307 状态代码的空响应实体

authorization - 访问 token 立即失效

rest - 刷新 Microsoft Live API 的 OAuth 访问 token

mysql - 如何向所有帖子添加具有随机值的自定义字段

mySQL:操作 '=' 的排序规则(utf8mb4_bin,IMPLICIT)和(utf8_general_ci,COERCIBLE)的非法混合

java - SpringBoot中找不到EntityManagerFactory