Keycloak,如何保护不为网页提供服务的Spring Boot后端?

问题描述 投票:0回答:1

我有一个前端,通过让我们的登录页面向Keycloak服务器发出POST请求来使用keycloak进行保护,因此可以获取访问令牌(JWT)。我们不使用kecloak提供的登录页面。该前端对后端(spring-boot)servlet进行REST调用,该servlet使用这些调用来查询数据库并将数据发送回前端。我看到的大多数关于保护spring-boot应用程序的教程都使用spring-boot服务于网页,并使用默认的keycloak登录页面。我的问题是,如何在不使用keycloak登录页面的情况下使用keycloak弹簧启动适配器?有什么方法可以在每个请求中传递密钥访问令牌,等同于密钥访问的期望?

我正在使用版本7.0.0的keycloak,并通过角色保护每个端点。

我已尽力按照本教程进行操作,除了我的@Controller用法不同,并且不使用任何spring-boot Model对象来提供网页服务,如前所述。当前,每个请求都返回500错误。因此,我想到了这个问题。https://www.thomasvitale.com/spring-boot-keycloak-security/

谢谢!

spring spring-boot jwt authorization keycloak
1个回答
0
投票

这个问题非常广泛,不能适用于Stackoverflow,但是最后Stackoverflow的平台可以互相帮助,所以这里是一个解决方案。

在您的rest api项目中,创建Keycloak功能类,该类将对所有即将获取数据的请求进行身份验证。

让我们来看看一种情况,假设我想在我的数据库中也在Keycloak中创建一个角色,我该怎么做?

假设请求将来自Rest Client或GUI->请求应包含令牌,因此每个请求都有一个有效的令牌,因此您在Keycloak DB中创建角色的代码将是这样的

public void createRole(String createRoleAPIurl,String accessToken){
RoleRepresentation roleRepresentation = new RoleRepresentation();
roleRepresentation.setName(role.getRoleName());
roleRepresentation.setDescription(role.getDescription());
String convertValue = mapper.writeValueAsString(roleRepresentation);
StringEntity entity = new StringEntity(convertValue);
response = keycloakUtil.fetchURLResponse(createRoleAPIurl, accessToken, entity);
}

public CloseableHttpResponse fetchURLResponse(String createRoleAPIurl, String accessToken, StringEntity entity)
            throws IOException, ClientProtocolException {
        CloseableHttpResponse response = null;
        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost postRequest = new HttpPost(url);
            postRequest.addHeader("Authorization", "bearer " + accessToken);
            postRequest.addHeader("content-type", "application/json");
            postRequest.setEntity(entity);
            response = httpclient.execute(postRequest);
        } catch (Exception e) {

        }
        return response;
    }

在此示例中,查询将转到Keycloak,因此url类似于https://<PORT>:<IP>/auth/roles此url,例如,在您的情况下,您必须编写另一种方法来验证令牌(如果将验证令牌),那么只有您才能允许请求从数据库中获取数据,否则您可能会抛出一些异常或传递消息。因此,您的每个请求都应该带有一个有效的令牌,现在它有责任验证令牌,然后仅允许访问您的资源。

希望它会帮助您。

© www.soinside.com 2019 - 2024. All rights reserved.