使用oauth在spring Boot 3中提取Keycloak Principal

k2arahey  于 2023-03-22  发布在  Spring
关注(0)|答案(1)|浏览(149)

有没有办法在spring Boot 3中使用oauth提取Keycloak Principal?
使用我们访问的旧版本,如下所示,

KeycloakAuthenticationToken authentication;
  try {
     authentication =
             (KeycloakAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
  } catch (ClassCastException exception) {
     throw new UnauthorizedException("Missing token");
  }
  Principal principal = (Principal) authentication.getPrincipal();
lrl1mhuk

lrl1mhuk1#

Keycloak的遗留API已经被弃用。您不需要KeycloakAuthenticationToken来提取主体。使用标准的spring oauth2代码,如

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication !=null) {
          Principal principal = (Principal) authentication.getPrincipal();
        }

相关问题