如何在AuditorAware中获取Keycloak用户名 [英] How to get Keycloak username in AuditorAware

查看:180
本文介绍了如何在AuditorAware中获取Keycloak用户名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经完全按照本文档的规定,使用Spring Data JPA实现了审核.当我运行该应用程序时,一切正常,但是当我将WAR部署到Tomcat并尝试创建实体时,在getCurrentAuditor方法中出现错误.

I have implemented Auditing with Spring Data JPA, following exactly this documentation. Everything works fine when I run the app, but when I deploy the WAR to Tomcat and try to create an entity, I get an error in the getCurrentAuditor method.

我已经用密钥斗篷保护了我的应用程序,因此在AuditorAwareConfig中,我试图获取密钥斗篷的用户名,并且在调试之后我发现request.getUserPrincipal()为null:

I have secured my app with keycloak, so in AuditorAwareConfig i am trying to get the keycloak username, and after debugging i found out that request.getUserPrincipal() is null :

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

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);
    }
}

推荐答案

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

I recently did the same thing in my applications but I didn't use the Keycloak adapter, Spring Security 5 provides all we need to secure our applications with Keycloak or with any Oauth2 provider. Another difference, I use Hibernate Envers, which allow me to also audit delete operations.

要获取经过身份验证的用户,这就是我的操作方法.

To get the authenticated user, this is how I proceed.

   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;
    }

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

Remember, I do not use the Keycloak Adapter.

这篇关于如何在AuditorAware中获取Keycloak用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆