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.
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
When you change the Access Type to "Bearer Only" in the settings of your client, you will get a nice 403.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.