Keycloak Admin client, 405 DELETE METHOD NOT ALLOWED - node.js

I am implementing a nodejs backend to manage users in Keycloak and for this I am using the npm package keycloak-nodejs-admin-client.
Everything works fine but when I started to try to delete resources I got 405 DELETE METHOD NOT ALLOWED
const adminClient = await initializeKeycloak()
let mapper = await adminClient.clientScopes.findProtocolMapperByName({id: openIdScopeId, name: keycloakId})
await adminClient.clientScopes.delProtocolMapper({id: openIdScopeId, name: mapper.name});
await adminClient.clientScopes.delProtocolMapper({id: samlScopeId, name: mapper.name});
For example the findProtocolMapperByName Works fine but the Delete does not and returns 405 I already tried to make sure I am using the library correctly so I think must be a keycloak configuration
This is how I configured the keycloak admin npm package:
kcAdminClient.setConfig({
realmName: 'master',
});
adminClient = await kcAdminClient.auth({
username: 'admin',
password: 'dummy',
grantType: 'password',
clientId:'admin-cli',
});
kcAdminClient.setConfig({
realmName: dummy,
});
the fact that I configure two realms is not affecting as this issue was happening before and I tried to use a user from Master realm to perform the request.
There is no information direct information on keycloak/http method and I think many a clarification of this can help lots of people, thanks!

I have found the issue: On the keycloak-nodejs-admin-client there is little docs and a test file to test the methods, there they user the mapper name to make the delete, in reality you need using the mapperID.

Related

Octokit-js based app throws JSON web token error

I'm having issues with an octokit-based nodejs app that was working just a couple of weeks ago. From nowhere, I'm getting auth errors that I've managed to debug to the point of getting this error message:
A JSON web token could not be decoded
This happens when I instanciate the Octokit for an installation App that works on Github and then ask anything of it (creating a PR, adding an issue, etc).
However, I'm not sure what does this mean. So far:
APP_ID and PRIVATE_KEY are variables stored in process.env.
The InstallationId I get from the Github app URL, and the other data (OWNER, REPO, etc) I've verified is correct.
This is a summarized version of my code:
const {Octokit} = require("#octokit/rest");
const { createAppAuth } = require("#octokit/auth-app");
const octokit = new Octokit({
authStrategy: createAppAuth,
auth: {
appId: APP_ID,
privateKey: PRIVATE_KEY,
// optional: this will make appOctokit authenticate as app (JWT)
// or installation (access token), depending on the request URL
installationId: process.env.INSTALLATION_ID,
},
});
const test = async()=>
await octokit.issues.create({
owner: OWNER,
repo: REPO,
title: "Hello world from me",
});
test()
What could be happening? Any help would be greatly appreciated.
Update:
I just tested this code on a different machine and... it works. So, I'm baffled as to why it is not running in the original machine.
I found the issue. The appId was wrong somehow. Quite embarrasing, but by testing on a new machine I just double checked all possible changes and found the issue.

Retrieve all registered users in firebase

I am using firebase database in nodejs.
I simply want to fetch all the users that exists in my firebase database.
Currently I am trying this but it is only return one single user:
var config = {
apiKey: "AIzaSyBmgbfgdhs4efg9gFo",
authDomain: "my-test-app.firebaseapp.com",
databaseURL: "https://my-test-app-default-rtdb.firebaseio.com",
projectId: "my-test-app",
storageBucket: "my-die-app.appspot.com",
messagingSenderId: "534345345",
appId: "1:534345345:web:cceb16e6vvdd456",
measurementId: "G-YDZ8Y87GETR",
};
firebase.initializeApp(config);
var ref = firebase.database().ref("users");
ref.once("value", function (snapshot) {
snapshot.forEach((child) => {
console.log(child)
});
});
In firebase users I can only see this single user aswell, but infact I have more users there:
{
"XG0hYDjhekjdfJX5zLmfUFPQBifkmZA3": [
"XG0hYDjhekjdfJX5zLmfUFPQBifkmZA3",
"user1#gmail.com",
"835457568",
"Michael James ",
"user1#gmail.com"
]
}
And this is the only user I am getting in code aswell.
I am not the owner of this database, may be thats the reason?
Is there any specific way to retrieve all users list?
I believe the question answers itself
In firebase users I can only see this single user
If there is only only user node in the /users node as shown in your question
users {
"XG0hYDjhekjdfJX5zLmfUFPQBifkmZA3": [
"XG0hYDjhekjdfJX5zLmfUFPQBifkmZA3",
"user1#gmail.com",
"835457568",
"Michael James ",
"user1#gmail.com"
]
}
that means only one node exists - therefore only one node can be retrieved.
The confusion may be that while Firebase has users that can authenticate, those users are stored in the Firebase back-end server only. It doesn't necessarily mean other user data was written to the /users node.
In other words, if the app code does not specifically write data to /users, it won't exist.
Check your authentication code and see if it writes data to /users at some point - if not, there's your problem.
If that's the issue, which I suspect it is, you can't retrieve a list of Firebase users from the SDK directly, but you can using Firebase Admin coupled with Cloud Functions.
Here's an example: Get All Users
Alternatively (and my suggested path), you can also add code to the app so when users authenticate, if their users node doesn't exist within /users, create it (using the users uid returned from the Auth parameter as the node key)
What user are you logged in as? Is that the user you can see? What are your Firebase security rules like?
If you have reasonably secure rules setup, that would be the reason users can only see their own nodes.
See these docs: https://firebase.google.com/docs/database/security#section-authorization

Heroku postgres timeout and SSL issues on API calls with Node

I'm trying to put my REST API built in Node and with PostgresSQL to Heroku. So, I created my application to Heroku, and created his own database. At this point, I tryied to commit, and the build worked corretly. This until I tryied to make some calls to the API. If the api calls I do has the uncorrect method, or doesn't exists, it gives me the correct error, but when the call is correct, there is a 503 error, with code H12, and description that is timeout error. Here is the code of one of the calls to the database that I'm testing:
router.get('/allpoints', async (req,res) =>{
try {
const points = await pool.query(
`SELECT nome, latitudine,longitudine
FROM luogo`);
res.json(points.rows);
}catch(err){
console.error(err.message);
}
});
Here there are the information about how I connect to the database.
const pool = new Pool({
connectionString: process.env.DATABASE_URL || 'postgresql://postgres:psw#localhost:5432/campione',
ssl: process.env.DATABASE_URL ? true : false
})
module.exports = pool;
The build on Heroku seems to work properly.
I read this question: Heroku h12 Timeout Error with PG / Node.js
It says that you have to put res.end() where there is not res.json(), but here there is the res.json(). So, I thought that the issue could be that there is an error that the route manage, and can't give back anything. So, I changed from console.log(err) to res.json(err), and the API response with `ssl self signed, as an error. At this point, in the second file, I put ssl as false by default, but it gaves me error because there is no SSL. I searched for a really long time for a solution, but I have not been able yet to fix the issue.
Someone thinks he knows what should I change? Thank you in advice
this option in databse config maybe useful
ssl: {
rejectUnauthorized : false,
}

How do I correctly authenticate in mongo for a user that has access to multiple databases?

I have a user with the role: {role: 'root', db:'admin'} which should have access to all the databases in my mongo instance. I'm using mongoskin in node.js to interact with mongo. My problem is that it isn't correctly accessing my databases. If I authenticate with
mongodb://owner:mylocalpassword#localhost:27017/mydatabase
It simply gives me MongoError: Authentication failed. If I instead auth with:
mongodb://owner:mylocalpassword#localhost:27017/admin
it authenticates, but I can't access mydatabase.
Here's my connection code:
var connection = mongoskin.db("mongodb://owner:mylocalpassword#localhost:27017/admin", {journal:true, auto_reconnect:true})
I assume that since I'm accessing the admin database there, that's the only one it interacts with. So I tried do then do this:
var mydatabaseConnection = connection.db('mydatabase')
But when I use that, my app is returning no results for queries on collections that I know have data. What am I doing wrong here? How do I get this user to access a database other than admin?
Ok, so I found out that mongoskin's db method simply doesn't work. Finally I'm forced to completely remove mongoskin from my codebase. The real answer here is don't use mongoskin.
This code worked with mongo native:
MongoClient.connect("mongodb://owner:mylocalpassword#localhost:27017/admin", {journal: true, auto_reconnect:true}).then(function(db) {
console.log("Connected!")
var mydb = db.db('mydatabase')
var User = mydb.collection('User')
return User.find({}).toArray().then(function(users) {
console.log(users)
db.close()
})
}).catch(function(e) {
console.log(e.stack)
})

unexpected `server_admin required` error with Cloudant NodeJS

I am using the Cloudant service via the Node.JS module, with the credentials provided via Bluemix VCAP_SERVICES (or a local copy). The instance is created with
var Cloudant = require('cloudant');
// var cloudantCreds obtained from process.env.VCAP_SERVICES
var username = cloudantCreds.username;
var password = cloudantCreds.password;
var cloudant = Cloudant({
account:username,
password:password
});
I had written a function that would automatically create/delete a database when a user requested, and it successfully worked. This internally used
cloudant.db.create(databaseName, function(err, res){
// Handle
});
However, recently I get an error:
'server_admin access is required for this request'
I am only using one set of credentials and one account. Using these credentials in the command line with curl allows me to successfully create/delete databases, but it seems to be unable to do this via the node.js module?
As far as I can remember, I haven't changed any code related to this function of my Node.js server.
What is causing me to now require server_admin access? From the nature of the error message, I am presumably authenticated, but not authorised?
It turns out it was an error on my behalf, although Cloudant was not particularly informative.
I was trying to create databases with disallowed names, such as beginning with an underscore or containing a capital letter. Change the database name, and it all works correctly.
if your database is prefixed with underscore it will throw errors...

Resources