Reputation: 93
I've been trying to integrate Keycloak into a simple node/express server so that I can authenticate with a bearer token in the header, but every protected request I'm making returns html(login page).
My simple index.js file:
const express = require('express');
const app = express();
const keycloak = require('./kc-config.js').initKeycloak();
app.use(keycloak.middleware());
app.get('/', (req, res) => {
res.send("Server is up!");
});
app.get('/kc-test', keycloak.protect(), (req, res) => {
res.send('success');
} )
app.listen(3000);
My simple kc-config.js file
var session = require('express-session');
var Keycloak = require('keycloak-connect');
let _keycloak;
var keycloakConfig = {
clientId: 'myclient',
bearerOnly: false,
serverUrl: 'http://my.client.com:4008/auth',
realm: 'master',
credentials: {
"secret": "{my-secret}"
}
};
function initKeycloak() {
if (_keycloak) {
console.warn("Trying to init Keycloak again!");
return _keycloak;
}
else {
console.log("Initializing Keycloak...");
memoryStore = new session.MemoryStore();
_keycloak = new Keycloak({ store: memoryStore }, keycloakConfig);
return _keycloak;
}
}
function getKeycloak() {
if (!_keycloak){
console.error('Keycloak has not been initialized. Please called init first.');
}
return _keycloak;
}
module.exports = {
initKeycloak,
};
I am using the token returned from this curl request:
curl -X POST 'http://my.client.com:4008/auth/realms/master/protocol/openid-connect/token'
--header 'Content-Type: application/x-www-form-urlencoded'
--data-urlencode 'grant_type=password'
--data-urlencode 'client_id=myclient'
--data-urlencode 'client_secret=mysecretkey'
--data-urlencode 'username=myusername'
--data-urlencode 'password=mypassword'
Shouldn't I be authorized? Why would it ask me to login again even though my token is valid?
For more information, here's a screenshot of my settings for my client, on the keycloak admin console.
I'm pretty confused. Am I using it completely wrong? My thought process was that I would be able to simply put the token from the curl request into the header of the request for the protected /kc-test route.
Upvotes: 0
Views: 1610
Reputation: 471
When you change the Access Type to "Bearer Only" in the settings of your client, you will get a nice 403. Keep in mind that this will not allow any requests without a valid bearer token (like obtaining the token itself).
The alternative is setting Access Type to "confidential" in the settings of your client and setting "bearerOnly": true
in your keycloak.json
(or keycloakConfig in your case).
Upvotes: 0
Reputation: 71
Access type of the client need to be bearer only.
{
"realm": "camunda",
"auth-server-url": "https://localhost:9000/auth/",
"ssl-required": "external",
"resource": "user-management",
"bearer_only":true,
"credentials": {
"secret": "45078604-3c4a-44a6-8a0f-ab094f050211"
},
"confidential-port": 0,
"policy-enforcer": {}
}
or you can set the bearer_only to true in you keycloak.json file
Upvotes: 0