我开发了一个Spring Boot Webservice并使用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
这是正确的方法吗?缺什么?
谢谢!
答案 0 :(得分:3)
我在代码中做了类似的事情。
public class AuthenticationTokenProcessingFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (!(request instanceof HttpServletRequest)) {
throw new RuntimeException("Expecting a HTTP request");
}
RefreshableKeycloakSecurityContext context = (RefreshableKeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
if (context == null) {
handleNoSecurityContext(request, response, chain);
return;
}
AccessToken accessToken = context.getToken();
Integer userId = Integer.parseInt(accessToken.getOtherClaims().get("user_id").toString());
chain.doFilter(request, response);
}
}
在执行此操作之前,您必须将user_id
添加到由keycloak发出的访问令牌中。您可以通过映射器执行此操作,如下面的屏幕截图所示。
此外,不要忘记通过向应用程序类添加@Bean
方法,将上面的处理过滤器添加到应用程序生命周期中。
@Configuration
@EnableAutoConfiguration(exclude = {FallbackWebSecurityAutoConfiguration.class, SpringBootWebSecurityConfiguration.class, DataSourceAutoConfiguration.class})
@ComponentScan
@EnableAsync
public class MyServiceClass {
public static void main(String[] args) {
Properties properties = new Properties();
new SpringApplicationBuilder(MyServiceClass.class)
.properties(properties)
.bannerMode(Banner.Mode.OFF)
.run(args);
}
@Bean
public AuthenticationTokenProcessingFilter authFilter() {
return new AuthenticationTokenProcessingFilter();
}
}
答案 1 :(得分:3)
我找到了一个比上述简单得多的解决方案:
@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())
可以工作。 / p>