OAuth2客户端凭据通过Spring Boot Keycloak集成进行流动

Ste*_*ich 6 java spring spring-boot keycloak

我的应用程序包括:

  • 后端/资源服务器
  • UI Webapp
  • 钥匙斗篷

UI正在使用具有授权码授予流程的keycloak客户端通过RESTful API与后端服务器进行通信。一切正常。

现在,我需要使用系统/服务帐户(通常具有比用户更多的权限)访问后端资源的其他可能性。您将如何实施此要求?我认为客户端凭据流在这里很有用。

是否可以将OAuth2客户端凭据流与用于keyboot客户端的Spring Boot一起使用?我发现了一些示例,这些示例使用Spring Security OAuth2客户端功能来实现客户端凭证流,但是这感觉很奇怪,因为我已经将keycloak客户端用于OAuth了。

编辑:解决方案

感谢您的回答,这对我很有帮助。现在,在我的UI Web应用程序中,我可以通过使用经过身份验证的用户OAuth2令牌或使用我的UI服务帐户的客户端凭据流中的令牌与后端进行通信。每种方法都有自己的RestTemplate,首先是通过整合keycloak完成,第二个是Spring Security中的OAuth2作为解释做

Ari*_*era 6

Yes, you can use OAuth 2.0 Client Credentials flow and Service Accounts.

Keycloak suggest 3 ways to secure SpringBoot REST services:

  1. with Keycloak Spring Boot Adapter
  2. with keycloak Spring Security Adapter
  3. with OAuth2 / OpenID Connect

Here is a good explanation about this with an example in the OAuth2/OIDC way:

If you follow this example, keep in mind:

Take care to configure your client as:

  • Access Type: Confidential
  • Authorization: Enabled
  • Service Account (OAuth Client Credentials Flow): Enabled

Take care to configure your target service as:

  • Access Type: Bearer-only

So, caller should be confidential and target service should be bearer-only.

Create your users, roles, mappers... and assign roles to your users.

Check that you have this dependencies in your spring project:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.security.oauth.boot</groupId>
  <artifactId>spring-security-oauth2-autoconfigure</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)

Configure authentication to be used in the REST client (application.properties) e.g.:

security.oauth2.client.client-id=employee-service
security.oauth2.client.client-secret=68977d81-c59b-49aa-aada-58da9a43a850
security.oauth2.client.user-authorization-uri=${rest.security.issuer-uri}/protocol/openid-connect/auth
security.oauth2.client.access-token-uri=${rest.security.issuer-uri}/protocol/openid-connect/token
security.oauth2.client.scope=openid
security.oauth2.client.grant-type=client_credentials
Run Code Online (Sandbox Code Playgroud)

Implement your JwtAccessTokenCustomizer and SecurityConfigurer (ResourceServerConfigurerAdapter) like Arun's sample.

And finally implement your service Controller:

@RestController
@RequestMapping("/api/v1/employees")
public class EmployeeRestController {

  @GetMapping(path = "/username")
  @PreAuthorize("hasAnyAuthority('ROLE_USER')")
  public ResponseEntity<String> getAuthorizedUserName() {
    return ResponseEntity.ok(SecurityContextUtils.getUserName());
  }

  @GetMapping(path = "/roles")
  @PreAuthorize("hasAnyAuthority('ROLE_USER')")
  public ResponseEntity<Set<String>> getAuthorizedUserRoles() {
    return ResponseEntity.ok(SecurityContextUtils.getUserRoles());
  }
}
Run Code Online (Sandbox Code Playgroud)

For a complete tutorial, please read the referred Arun's tutorial.

Hope it helps.


Car*_*ero 5

按照@dmitri-algazin 实施工作流程,您基本上有两个选择:

  1. 如果您想涵盖除 Keycloak 之外的其他 IdM,它以某种方式解决了单一责任原则,我会使用RestTemplate. 您可以在下面找到变量:
    //Constants
    @Value("${keycloak.url}")
    private String keycloakUrl;

    @Value("${keycloak.realm}")
    private String keycloakRealm;

    @Value("${keycloak.client_id}")
    private String keycloakClientId;

    RestTemplate restTemplate = new RestTemplate();
    private static final String BEARER = "BEARER ";
Run Code Online (Sandbox Code Playgroud)

首先,您需要生成访问令牌:

    @Override
    public AccessTokenResponse login(KeycloakUser user) throws NotAuthorizedException {
        try {
            String uri = keycloakUrl + "/realms/" + keycloakRealm + 
                    "/protocol/openid-connect/token";
            String data = "grant_type=password&username="+
                    user.getUsername()+"&password="+user.getPassword()+"&client_id="+
                    keycloakClientId;

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/x-www-form-urlencoded");

            HttpEntity<String> entity = new HttpEntity<String>(data, headers);
            ResponseEntity<AccessTokenResponse> response = restTemplate.exchange(uri, 
                    HttpMethod.POST, entity, AccessTokenResponse.class);            

            if (response.getStatusCode().value() != HttpStatus.SC_OK) {
                log.error("Unauthorised access to protected resource", response.getStatusCode().value());
                throw new NotAuthorizedException("Unauthorised access to protected resource");
            }
            return response.getBody();
        } catch (Exception ex) {
            log.error("Unauthorised access to protected resource", ex);
            throw new NotAuthorizedException("Unauthorised access to protected resource");
        } 
    }
Run Code Online (Sandbox Code Playgroud)

然后使用令牌,您可以从用户那里检索信息:

    @Override
    public String user(String authToken) throws NotAuthorizedException {

        if (! authToken.toUpperCase().startsWith(BEARER)) {
            throw new NotAuthorizedException("Invalid OAuth Header. Missing Bearer prefix");
        }

        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", authToken);

        HttpEntity<String> entity = new HttpEntity<>(headers);

        ResponseEntity<AccessToken> response = restTemplate.exchange(
                keycloakUrl + "/realms/" + keycloakRealm + "/protocol/openid-connect/userinfo", 
                HttpMethod.POST, 
                entity, 
                AccessToken.class);

        if (response.getStatusCode().value() != HttpStatus.SC_OK) {
            log.error("OAuth2 Authentication failure. "
                    + "Invalid OAuth Token supplied in Authorization Header on Request. Code {}", response.getStatusCode().value());
            throw new NotAuthorizedException("OAuth2 Authentication failure. "
                    + "Invalid OAuth Token supplied in Authorization Header on Request.");
        }

        log.debug("User info: {}", response.getBody().getPreferredUsername());
        return response.getBody().getPreferredUsername();
    }
Run Code Online (Sandbox Code Playgroud)

您可以将此 URL 替换为 @dimitri-algazin 提供的 URL,以检索所有用户信息。

  1. 可以使用 Keycloak 依赖项:
        <!-- keycloak -->
        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-admin-client</artifactId>
            <version>3.4.3.Final</version>
        </dependency>

        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-client</artifactId>
            <version>3.1.4.Final</version>
        </dependency>
Run Code Online (Sandbox Code Playgroud)

并使用类来生成令牌:

            Keycloak keycloak = KeycloakBuilder
                    .builder()
                    .serverUrl(keycloakUrl)
                    .realm(keycloakRealm)
                    .username(user.getUsername())
                    .password(user.getPassword())
                    .clientId(keycloakClientId)
                    .resteasyClient(new ResteasyClientBuilder().connectionPoolSize(10).build())
                    .build();

            return keycloak.tokenManager().getAccessToken();
Run Code Online (Sandbox Code Playgroud)

示例摘自此处。我们还将镜像上传到 Docker Hub,以方便与 Keycloak 交互。因此我们从选项 2) 开始。目前,我们正在覆盖其他 IdM,我们选择了选项 1),以避免包含额外的依赖项。结论:

如果您坚持使用 Keycloak,我会选择选项 2 ,因为类包含 Keycloak 工具的额外功能。我会选择选项 1以获得更多的覆盖范围和其他 OAuth 2.0 工具。