gpt4 book ai didi

java - Spring key 斗篷 : Get User ID

转载 作者:搜寻专家 更新时间:2023-10-31 19:31:59 27 4
gpt4 key购买 nike

我开发了一个 Spring Boot Web 服务并使用 Keycloak 进行访问管理。该网站将一些用户数据存储在数据库中。我尝试将这些数据与登录的用户联系起来。

目前我将用户名与数据一起存储。但我喜欢存储用户 ID 而不是用户名。我怎样才能做到这一点?

我尝试通过这个获取 SecurityContext:

@Bean
@Scope(scopeName = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public KeycloakSecurityContext getKeycloakSecurityContext() {
return ((KeycloakPrincipal<KeycloakSecurityContext>) getRequest().getUserPrincipal()).getKeycloakSecurityContext();
}

但是我得到一个错误:

There was an unexpected error (type=Internal Server Error, status=500).
Error creating bean with name 'scopedTarget.getKeycloakSecurityContext'
defined in com.SiteApplication: Bean instantiation via factory method
failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [org.keycloak.KeycloakSecurityContext]: Factory method
'getKeycloakSecurityContext' threw exception; nested exception is
java.lang.ClassCastException:
org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken
cannot be cast to org.keycloak.KeycloakPrincipal

这是正确的方法吗?什么东西少了?

谢谢!

最佳答案

我找到了一个比上面简单得多的解决方案:

    @GetMapping
public ResponseEntity getEndpoint(String someParam, HttpServletRequest request) {
KeycloakAuthenticationToken principal = (KeycloakAuthenticationToken) request.getUserPrincipal();
String userId = principal.getAccount().getKeycloakSecurityContext().getIdToken().getSubject();

//....do something

return new ResponseEntity(HttpStatus.OK);
}

我认为你遇到的异常是因为你试图转换 getRequest().getUserPrincipal()KeycloakPrincipal<KeycloakSecurityContext>而它的类型是 KeycloakAuthenticationToken , 所以 ((KeycloakAuthenticationToken) getRequest().getUserPrincipal())会工作。

关于java - Spring key 斗篷 : Get User ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45802797/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com