Reputation: 11
I have a problem with keycloak.protect(), I can't access my "/secured" route. Indeed, when I try to access it from my frontend, I have the CORS blocking me. However, I made sure with app.use(cors()) to allow everything. I also tested if I can get my token id from my frontend (I get it fine.) Do you have any idea what could be blocking?
My code to illustrate my point:
index.ts
import bodyParser from 'body-parser';
import cors from 'cors';
import express from 'express';
import KeycloakConnect from 'keycloak-connect';
const session = require('express-session');
const Keycloak = KeycloakConnect;
const app = express();
app.use(cors())
app.options('*', cors());
app.use(bodyParser.json());
const memoryStore = new session.MemoryStore();
app.use(session({
secret: 'mysecret',
resave: false,
saveUninitialized: true,
store: memoryStore
}));
const keycloak = new Keycloak({store: memoryStore});
app.use(keycloak.middleware({
logout: "/logout",
admin: "/"
}));
app.use(cors());
app.get('/service/public', function (req, res) {
console.log('Server started on port 3000');
});
app.get('/secured', keycloak.protect(), function (req, res) {
console.log('Server started on port 3000');
});
app.get('/service/admin', keycloak.protect('realm:admin'), function (req, res) {
res.json({message: 'admin'});
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
keycloak.json
{
"realm": "QRCoffee",
"auth-server-url": "http://localhost:8080/auth",
"ssl-required": "external",
"resource": "QRCoffee",
"public-client": true,
"confidential-port": 0
}
Error CORS
Access to fetch at 'http://localhost:8080/auth/realms/QRCoffee/protocol/openid-connect/auth?client_id=QRCoffee&state=7321400d-3c51-4c53-8c9a-100101239845&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fsecured%3Fauth_callback%3D1&scope=openid&response_type=code' (redirected from 'http://localhost:3000/secured') from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I would like to access my /secured route when I am connected to keycloak.
Upvotes: 1
Views: 231