java - 如何在 AuditorAware 中获取 Keycloak 用户名

标签 java spring spring-boot tomcat keycloak

我已经使用 Spring Data JPA 实现了审计,完全遵循 this documentation .运行应用程序时一切正常,但是当我将 WAR 部署到 Tomcat 并尝试创建实体时,我在 getCurrentAuditor 中收到错误消息。方法。
我已经用 keycloak 保护了我的应用程序,所以在 AuditorAwareConfig我正在尝试获取 keycloak 用户名,经过调试我发现 request.getUserPrincipal()一片空白 :

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

最佳答案

TL;博士 — 在 application.properties 文件中,添加 keycloak.principal-attribute=preferred_username . 有条件 ,你可能还需要设置keycloak.public-client=false (或完全删除它)。

长篇版本
根据 your other Keycloak-related question

This is my Spring Configuration :

application.properties:

keycloak.realm=cirta
keycloak.auth-server-url=http://localhost:8085/auth
keycloak.resource=cirta-api
keycloak.public-client=true
keycloak.cors=true    
keycloak.bearer-only=true


你可能需要把它改成这个……
keycloak.realm=cirta
keycloak.auth-server-url=http://localhost:8085/auth
keycloak.resource=cirta-api
keycloak.public-client=false # or delete the property, since false is the default
keycloak.cors=true    
keycloak.bearer-only=true
keycloak.principal-attribute=preferred_username # add this


TL;博士 我合格了我的 public-client建议为“有条件”。我的意思是在添加 keycloak.principal-attribute 之后属性(property),你可能需要尝试切换 keycloak.public-client开和关;取决于哪种设置适用于您的特定设置。
引用 the Keycloak docs更多细节…

public-client

If set to true, the adapter will not send credentials for the client to Keycloak. This is OPTIONAL. The default value is false.

principal-attribute

OpenID Connect ID Token attribute to populate the UserPrincipal name with. If token attribute is null, defaults to sub. Possible values are sub, preferred_username, email, name, nickname, given_name, family_name.

关于java - 如何在 AuditorAware 中获取 Keycloak 用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64153617/

相关文章:

java - Spring 启动: Best way to return 503 HttpStatus in ResponseEntity if the DataSource is DOWN

java - 如何在 JTextfied 中只接受 0 到 8 之间的数值?

java - Spring Executors - 在具有特定索引的线程中执行方法

java - 将数据保存到表中并将其保存到数据库中,即使 EXCEL 中为空行 java POI Apache

java - 嵌入式代理 ActiveMQ 的配置

java - Spring Boot 和 buildResponseEntity()

java - 如何从算术运算中得到实际的计算值

Java - 为什么我的冒泡排序比插入排序更快?

java - HQL 可完美运行嵌套 SQL

java - 错误由: java. lang.ClassNotFoundException : org. springframework.security.context.DelegatingApplicationListener引起