我已经使用 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 aresub
,preferred_username
,name
,nickname
,given_name
,family_name
.…
关于java - 如何在 AuditorAware 中获取 Keycloak 用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64153617/