Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#1236 Set up Client Credentials Flow for internal service communication in Keycloak #1251

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion common-library/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
<sonar.organization>nashtech-garage</sonar.organization>
<sonar.host.url>https://sonarcloud.io</sonar.host.url>
<sonar.projectKey>nashtech-garage_yas-common-library</sonar.projectKey>
<org.keycloak.version>16.1.0</org.keycloak.version>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you explain the reason for not using the same version as the parent's pom.xml?

</properties>
<dependencies>
<dependency>
Expand All @@ -37,6 +38,11 @@
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-admin-client</artifactId>
<version>${org.keycloak.version}</version>
</dependency>

<!-- Kafka Dependencies -->
<dependency>
Expand Down Expand Up @@ -81,4 +87,4 @@
</plugins>
</build>

</project>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.yas.commonlibrary.config;

import static org.keycloak.OAuth2Constants.CLIENT_CREDENTIALS;

import org.keycloak.admin.client.Keycloak;
import org.keycloak.admin.client.KeycloakBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class KeycloakClientConfig {
private static final String AUTH_SERVER_URL = "http://identity";
private static final String REALM = "Yas";
private static final String RESOURCE = "service-to-service";
private static final String CLIENT_SECRET = "6A1IpjtpvPYWzdLgi8j2zzVMlkjSGtBa";

@Bean
public Keycloak keycloak() {
return KeycloakBuilder.builder()
.grantType(CLIENT_CREDENTIALS)
.serverUrl(AUTH_SERVER_URL)
.realm(REALM)
.clientId(RESOURCE)
.clientSecret(CLIENT_SECRET)
.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.yas.commonlibrary.utils;

import jakarta.annotation.PostConstruct;
import org.keycloak.admin.client.Keycloak;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class KeycloakUtils {

private static Keycloak keycloakClient;

@Autowired
private Keycloak keycloak;

@PostConstruct
public void init() {
KeycloakUtils.keycloakClient = keycloak;
}

public static String getAccessToken() {
if (keycloakClient == null) {
throw new IllegalStateException("Keycloak client not initialized");
}
return keycloakClient.tokenManager().getAccessTokenString();
}
}
45 changes: 45 additions & 0 deletions common-library/src/test/java/utils/KeycloakUtilsTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package utils;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;

import com.yas.commonlibrary.utils.KeycloakUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.keycloak.admin.client.Keycloak;
import org.keycloak.admin.client.token.TokenManager;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
public class KeycloakUtilsTest {
@Mock
private Keycloak keycloak;

@Mock
private TokenManager tokenManager;

@InjectMocks
private KeycloakUtils keycloakUtils;


@BeforeEach
public void setUp() {
keycloakUtils.init();

// Mock the tokenManager to return the mocked TokenManager
when(keycloak.tokenManager()).thenReturn(tokenManager);
}

@Test
public void testGetAccessToken() {
String mockAccessToken = "mock-access-token";
when(tokenManager.getAccessTokenString()).thenReturn(mockAccessToken);

String accessToken = KeycloakUtils.getAccessToken();

assertEquals(mockAccessToken, accessToken);
}
}
97 changes: 97 additions & 0 deletions identity/realm-export.json
Original file line number Diff line number Diff line change
Expand Up @@ -979,6 +979,103 @@
"microprofile-jwt"
]
},
{
"id": "52a7918d-8a6c-49be-9659-d2a211e932f0",
"clientId": "service-to-service",
"name": "",
"description": "",
"rootUrl": "",
"adminUrl": "",
"baseUrl": "",
"surrogateAuthRequired": false,
"enabled": true,
"alwaysDisplayInConsole": false,
"clientAuthenticatorType": "client-secret",
"secret": "6A1IpjtpvPYWzdLgi8j2zzVMlkjSGtBa",
"redirectUris": [
"/*"
],
"webOrigins": [
"/*"
],
"notBefore": 0,
"bearerOnly": false,
"consentRequired": false,
"standardFlowEnabled": false,
"implicitFlowEnabled": false,
"directAccessGrantsEnabled": false,
"serviceAccountsEnabled": true,
"publicClient": false,
"frontchannelLogout": true,
"protocol": "openid-connect",
"attributes": {
"oidc.ciba.grant.enabled": "false",
"oauth2.device.authorization.grant.enabled": "false",
"client.secret.creation.time": "1730187207",
"backchannel.logout.session.required": "true",
"backchannel.logout.revoke.offline.tokens": "false"
},
"authenticationFlowBindingOverrides": {},
"fullScopeAllowed": true,
"nodeReRegistrationTimeout": -1,
"protocolMappers": [
{
"id": "ee203be7-aca5-44cb-b0be-4450937778ef",
"name": "Client ID",
"protocol": "openid-connect",
"protocolMapper": "oidc-usersessionmodel-note-mapper",
"consentRequired": false,
"config": {
"user.session.note": "clientId",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "clientId",
"jsonType.label": "String"
}
},
{
"id": "ef29968a-edb7-4a01-9182-91e36656540a",
"name": "Client Host",
"protocol": "openid-connect",
"protocolMapper": "oidc-usersessionmodel-note-mapper",
"consentRequired": false,
"config": {
"user.session.note": "clientHost",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "clientHost",
"jsonType.label": "String"
}
},
{
"id": "4d708db8-b5a7-49c7-8838-31f780983d26",
"name": "Client IP Address",
"protocol": "openid-connect",
"protocolMapper": "oidc-usersessionmodel-note-mapper",
"consentRequired": false,
"config": {
"user.session.note": "clientAddress",
"id.token.claim": "true",
"access.token.claim": "true",
"claim.name": "clientAddress",
"jsonType.label": "String"
}
}
],
"defaultClientScopes": [
"web-origins",
"acr",
"roles",
"profile",
"email"
],
"optionalClientScopes": [
"address",
"phone",
"offline_access",
"microprofile-jwt"
]
},
{
"id": "4f64c142-0545-44bb-9446-2a18b9c9effd",
"clientId": "storefront-bff",
Expand Down
2 changes: 1 addition & 1 deletion order/src/main/java/com/yas/order/OrderApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

@SpringBootApplication
@SpringBootApplication(scanBasePackages = {"com.yas.order", "com.yas.commonlibrary"})
@EnableConfigurationProperties(ServiceUrlConfig.class)
public class OrderApplication {

Expand Down
Loading