简体   繁体   English

Spring Keycloak - 如何从 JWT 访问令牌设置主体

[英]Spring Keycloak - How to set principal from JWT access token

I've been at this for about a week now.我已经在这大约一个星期了。

I have a use case where I recieve an auth token through the body instead of the header, and because of that Keycloak and Spring don't automatically set the user.我有一个用例,我通过主体而不是标头接收身份验证令牌,因此 Keycloak 和 Spring 不会自动设置用户。 (The reason being, with websockets, I can only send the auth token through the body with the initial connection) (原因是,使用 websockets,我只能通过具有初始连接的主体发送身份验证令牌)

I've tried intercepting the call before keycloak and copying the token from the body to the header, but that did not work.我试过在 keycloak 之前拦截调用并将令牌从正文复制到标题,但这不起作用。

So now I would like to manually authenticate through keycloak (or just manually set the principal user).所以现在我想通过 keycloak 手动进行身份验证(或者只是手动设置主体用户)。 I have access to the JWT Access Token, but from here I'm not sure how to authenticate with keycloak.我可以访问 JWT 访问令牌,但从这里我不确定如何使用 keycloak 进行身份验证。

Anyone have any input?有人有任何意见吗?

Since there are two Keycloak pieces that could be in play here, I'll start with a clarification:由于有两个 Keycloak 部件可以在这里发挥作用,我首先要澄清一下:

  • Keycloak - This is the authorization server that a client will use to obtain a JWT Keycloak - 这是客户端将用来获取 JWT 的授权服务器
  • Keycloak Adapter - This is the thing that configures a Resource Server to integrate Keycloak with Spring Security Keycloak Adapter - 这是配置资源服务器以将 Keycloak 与 Spring Security 集成的东西

I have a use case where I recieve an auth token through the body instead of the header, and because of that Keycloak and Spring don't automatically set the user.我有一个用例,我通过主体而不是标头接收身份验证令牌,因此 Keycloak 和 Spring 不会自动设置用户。

Spring Security 5.1 ships with built-in support for JWT-based access tokens, so you may not need to use the Keycloak Adapter for what you are wanting to do. Spring Security 5.1 附带对基于 JWT 的访问令牌的内置支持,因此您可能不需要使用 Keycloak Adapter 来完成您想要做的事情。

When using Spring Security's built-in support, you can configure the DefaultBearerTokenResolver to look in the body:在使用 Spring Security 的内置支持时,可以配置DefaultBearerTokenResolver来查看正文:

@Bean
public BearerTokenResolver bearerTokenResolver() {
    DefaultBearerTokenResolver resolver =
            new DefaultBearerTokenResolver();
    resolver.setAllowFormEncodedBodyParameter(true);
    return resolver;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM