如何在 AuditorAware 中获取 Keycloak 用户名

Bil*_*KAR 5 java spring tomcat spring-boot keycloak

我已经使用 Spring Data JPA 实现了审计,完全遵循此文档。当我运行应用程序时,一切正常,但是当我将 WAR 部署到 Tomcat 并尝试创建实体时,我在方法中收到错误getCurrentAuditor

我已经用 keycloak 保护了我的应用程序,所以AuditorAwareConfig我试图获取 keycloak 用户名,调试后我发现它request.getUserPrincipal()是 null :

java.lang.NullPointerException: null
    at com.cevital.cirta.util.AuditorAwareConfig.getCurrentAuditor(AuditorAwareConfig.java:20) ~[classes/:0.0.1-SNAPSHOT
Run Code Online (Sandbox Code Playgroud)

AuditorAwareConfig:

public class AuditorAwareConfig implements AuditorAware<String> {
    @Autowired
    private HttpServletRequest request;

    @Override
    public Optional<String> getCurrentAuditor() {
        KeycloakPrincipal<KeycloakSecurityContext> kp = (KeycloakPrincipal<KeycloakSecurityContext>) request.getUserPrincipal();
        String userName = kp.getKeycloakSecurityContext().getToken().getPreferredUsername();
        return Optional.ofNullable(userName);
    }
}
Run Code Online (Sandbox Code Playgroud)

aku*_*ma8 4

我最近在我的应用程序中做了同样的事情,但我没有使用 Keycloak 适配器,Spring Security 5 提供了我们使用 Keycloak 或任何 Oauth2 提供程序来保护我们的应用程序所需的一切。另一个区别是,我使用 Hibernate Envers,它还允许我审核删除操作。

为了获得经过身份验证的用户,这就是我的操作方式。

   public static String extractUsernameFromAuthentication() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username;
        if ( isNull( authentication ) ) {
            return null;
        }
        if ( authentication instanceof JwtAuthenticationToken ) {
            JwtAuthenticationToken token = (JwtAuthenticationToken) authentication;
            username = (String) ( token ).getTokenAttributes().get( "preferred_username" );
        } else {
            username = authentication.getName();
        }
        return username;
    }
Run Code Online (Sandbox Code Playgroud)

请记住,我不使用 Keycloak 适配器。