弹簧钥匙斗篷:获取用户 ID

2022-09-03 04:23:13

我开发了一个Spring Boot Webservice,并使用Keycloak进行访问管理。该网站将一些用户数据存储在数据库中。我尝试将这些数据与登录的用户连接。

目前,我将用户名与数据一起存储。但我喜欢存储用户ID而不是用户名。我该怎么做?

我试图通过这个来获得安全上下文:

@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

这是正确的方法吗?缺少什么?

谢谢!


答案 1

我发现了一个比上面更简单的解决方案:

    @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())


答案 2

我在代码中也做过类似的事情。

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

configuration for property mapper

此外,不要忘记通过向应用程序类添加方法,从上面将处理筛选器添加到应用程序生命周期中。@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();
    }

}

推荐