@@ -60,6 +60,11 @@ public Map<String, List<String>> getUserAttributes(String userId) {
6060 */
6161 public boolean validateJwt (String token ) {
6262 try {
63+ if (token .startsWith ("Bearer " )) {
64+ token = token .substring (7 );
65+ }
66+
67+ token = token .trim ().replaceAll ("\\ s+" , "" ); // remove all whitespace
6368 var kid = JwtUtil .extractKid (token );
6469 Objects .requireNonNull (kid , "No 'kid' found in JWT header" );
6570 var publicKey = keycloak .getPublicKey (kid );
@@ -79,6 +84,11 @@ public boolean validateJwt(String token) {
7984 * Extract the client ID (agent identity) from a valid JWT.
8085 */
8186 public String extractAgentId (String token ) {
87+ if (token .startsWith ("Bearer " )) {
88+ token = token .substring (7 );
89+ }
90+
91+ token = token .trim ().replaceAll ("\\ s+" , "" ); // remove all whitespace
8292 var kid = JwtUtil .extractKid (token );
8393 Objects .requireNonNull (kid , "No 'kid' found in JWT header" );
8494 var publicKey = keycloak .getPublicKey (kid );
@@ -93,6 +103,11 @@ public String extractAgentId(String token) {
93103 }
94104
95105 public String extractUsername (String token ) {
106+ if (token .startsWith ("Bearer " )) {
107+ token = token .substring (7 );
108+ }
109+
110+ token = token .trim ().replaceAll ("\\ s+" , "" ); // remove all whitespace
96111 var kid = JwtUtil .extractKid (token );
97112 Objects .requireNonNull (kid , "No 'kid' found in JWT header" );
98113 var publicKey = keycloak .getPublicKey (kid );
@@ -119,6 +134,13 @@ public void removeAgentClient(String clientId) {
119134 public AgentRegistrationDTO registerAgentClient (AgentRegistrationDTO agent ) {
120135 ClientsResource clients = keycloak .getKeycloak ().realm (realm ).clients ();
121136
137+ List <ClientRepresentation > existingClients = clients .findByClientId (agent .getAgentName ());
138+ if (!existingClients .isEmpty ()) {
139+ String existingClientId = existingClients .get (0 ).getId ();
140+ log .warn ("Client with ID '{}' already exists. Removing before re-registration." , agent .getAgentName ());
141+ clients .get (existingClientId ).remove ();
142+ }
143+
122144 // Step 1: Build client representation
123145 ClientRepresentation client = new ClientRepresentation ();
124146 client .setClientId (agent .getAgentName ());
0 commit comments