Keycloak Exchange Token

129 views
Skip to first unread message

Aurunisbi Aldino Aulia

unread,
Nov 7, 2024, 10:04:31 PM11/7/24
to Keycloak User
Hi There,

Can somebody explain me why can't I exchange token from public client to private client?
I have web(public client) and backend services(private client). When i login in web I've got the token and want to exchange the token in order to access to the backend services.
The error says:
 Token exchange error: {"error":"access_denied","error_description":"not_authorized"}

Here's my function.
const exchangeToken = (publicToken: any, clientId: any, clientSecret: any): Promise<string> => {
return new Promise((resolve, reject) => {
let params = 'grant_type=urn:ietf:params:oauth:grant-type:uma-ticket';
params += `&audience=${clientId}`;
const req = new XMLHttpRequest();
req.onreadystatechange = () => {
if (req.readyState === 4) {
if (req.status === 200) {
try {
const response = JSON.parse(req.responseText);
resolve(response.access_token);
} catch (error) {
console.error('Error parsing response:', error);
reject(new Error('Token exchange failed: Invalid JSON response'));
}
} else {
console.error('Token exchange error:', req.responseText);
reject(new Error('Token exchange failed: ' + req.statusText));
}
}
};

req.open('POST', `${process.env.REACT_APP_KEYCLOAK_BASE_URL}/realms/${process.env.REACT_APP_KEYCLOAK_REALM}/protocol/openid-connect/token`, true);
req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
req.setRequestHeader('Authorization', 'Bearer ' + String(publicToken));
req.send(params.toString());
});
};

ravt...@gmail.com

unread,
Nov 7, 2024, 11:37:09 PM11/7/24
to Keycloak User
You can find the reason behind not allowing token exchange with public clients Token Exchange
Reply all
Reply to author
Forward
0 new messages