LDAP get full name and email nodejs - node.js

I am writing app in node js. For login I would like use active directory. I found this package. Authentication is ok, but I cannot get user full name and email. There is my code:
var ActiveDirectory = require('activedirectory2');
var ActiveDirectory = require('activedirectory2');
var _ = require('underscore');
var query = 'cn=*Exchange*';
var opts = {
includeMembership : [ 'all' ],
includeDeleted : false
};
var config = {
url: 'ldap://dc.in.domain.cz',
baseDN: 'CN=Users,DC=in,DC=domain,DC=cz',
bindDN: 'CN=searchuser,CN=users,DC=in,DC=domain,DC=cz'
};
var ad = new ActiveDirectory(config);
var username = 'username #in.domain.cz';
var password = 'my_password';
ad.authenticate(username, password, function (err, auth) {
if (auth) {
console.log('Authenticated!');
ad.find(query, function (err, results) {
if ((err) || (!results)) {
console.log('ERROR: ' + JSON.stringify(err));
return;
}
console.log('Users');
_.each(results.users, function (user) {
console.log(' ' + user.cn);
});
});
} else {
console.log('Authentication failed!');
}
});
I get error:
ERROR: {"lde_message":"000004DC: LdapErr: DSID-0C0907C2, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, v2580\u0000","lde_dn":null}
Thank you

The authenticate function is just used for testing if credentials are valid. You would use this if, for example, you have a login page and you want to see if the credentials the user gave you are correct. These credentials are not used for the other operations.
In the documentation, it says under the Usage heading:
The username and password specified in the configuration are what are used for user and group lookup operations.
So when you use find(), it's using the credentials you put in config. You have bindDN there, but you don't have password, which is likely why the bind failed. You will need to add the password for that "searchuser" account:
var config = {
url: 'ldap://dc.in.domain.cz',
baseDN: 'CN=Users,DC=in,DC=domain,DC=cz',
bindDN: 'CN=searchuser,CN=users,DC=in,DC=domain,DC=cz',
password: 'something'
};
Note that the docs say that you can also use the username property instead of bindDN, but don't think there is any functional difference except being able to just specify the username and not the whole DN:
var config = {
url: 'ldap://dc.in.domain.cz',
baseDN: 'CN=Users,DC=in,DC=domain,DC=cz',
username: 'searchuser#in.domain.cz',
password: 'something'
};

Related

If MFA enabled in AWS cognito, do I need to create js on client side to call cognitoUser.authenticateUser() because of the promt for code?

I am using reactjs and node for server side.
As you can see in the "mfa required" part of the code below, if this is all on node, then I can't really do "prompt" the user for the code, I have to pass this back to the front end.
Tried solution: If I do pass the MFA required to front end and get the users input then send it back to node to call "respondToAuth" I am getting two MFA codes in my SMS message.
Have I tried other solutions?
I am hesitant to use amplify because everything is on the front end, I would ideally like to do my authentication on the back end (thus node).
Another option I am leaning towards is just using initiateAuth api instead of "cognitoUser.AuthenticateUser". This way I can get the challenge response and pass it on in sequence. But as per my initial question, I am wondering if I can implement the below code and be able to route users to input MFA code (without duplicating MFA sms message)
AWS.config.update({
region: process.env.Region
});
var AmazonCognitoIdentity = require('amazon-cognito-identity-js');
const poolData = { //--Moved to env variables
UserPoolId: process.env.UserPoolId, // your user pool id here
ClientId: process.env.ClientId // your app client id here
};
const userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
router.post('/api/authenticateuser', (req, res) => {
const val = req.body;
var userData = {
Username: val.value.user, // your username here
Pool: userPool
};
var authenticationData = {
Username: val.value.user, // your username here
Password: val.value.pass, // your password here
};
const authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);
const cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function(result) {
console.log('You are now logged in.');
console.log(result);
const accessToken = result.getAccessToken().getJwtToken();
const idToken = result.getIdToken().getJwtToken();
res.json({
accessToken,
idToken
});
},
onFailure: function(err) {
res.json(err);
},
mfaRequired: function(codeDeliveryDetails) {
// console.log("mfa enabled");
// var verificationCode = prompt('Please input verification code' ,'');
// cognitoUser.sendMFACode(verificationCode, this);
// res.json({ MFA:codeDeliveryDetails})
}
});
})

AWS Cognito Node.JS User Authentication returns unknown problem

I'm using AWS Cognito with Node.JS.
I'm successfully registering and verifying users, but the Authentication is returning "unknown error, the response body from fetch is undefined."
I'm using node-fetch module along with amazon-cognito-identity-js (set as var AWSCognito on code below). User is not in a state of requiring password change and verified.
Have others experienced this and how did you resolve the issue?
Appreciate any guidance in advance....
Here's my code, my complete module is on npm as iditawsutils :
exports.authCognitoUser = function(theUserPoolID, theClientID, userName, userPassword) {
var authenticationData = {
Username : userName,
Password : userPassword
};
var authenticationDetails = new AWSCognito.AuthenticationDetails(authenticationData);
var poolData = { UserPoolId : theUserPoolID,
ClientId : theClientID
};
var userPool = new AWSCognito.CognitoUserPool(poolData);
var userData = {
Username : userName,
Pool : userPool
};
console.log('authentication details: ',authenticationDetails);
var cognitoUser = new AWSCognito.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
console.log('access token + ' + result.getAccessToken().getJwtToken());
console.log('id token + ' + result.getIdToken().getJwtToken());
console.log('refresh token + ' + result.getRefreshToken().getToken());
return result;
},
onFailure: function(err) {
console.log(err.message || JSON.stringify(err));
return err;
},
});
}
//from the console log:
authentication details: AuthenticationDetails {
validationData: {},
authParameters: {},
username: 'thesmarterstuff',
password: 'passW0rd!’ }
Unknown error, the response body from fetch is: undefined
Use the following in your onFailure block to find more details about the error.
onFailure: function(err) {
console.log(new Error().stack);
console.log(err.message || JSON.stringify(err));
},
If you find the error occurring in your fetch line in Client.js, then this could be because currently NodeJS SDK, and most other SDKs do not support the default USER_SRP_AUTH.
You could check by adding a console.log in the Client.js
console.log(this.endpoint);
console.log(options);
Login to your AWS account, and make sure you have checked the option - Enable username-password (non-SRP) flow for app-based authentication (USER_PASSWORD_AUTH)
Then, in your code update it with the following setting.
cognitoUser.setAuthenticationFlowType('USER_PASSWORD_AUTH');

How to connect and find a user from Azure AD using Nodejs

I am trying to find a user from the azure active directory using nodejs. I am using Node-ActiveDirectory for this task. First I tried to connect to the Azure active directory as the given example in the above link. example code as below that I have used.
var ActiveDirectory = require('activedirectory');
var config = { url: 'ldap://myhotmail.onmicrosoft.com',
baseDN: 'dc=myhotmail,dc=onmicrosoft,dc=com',
username: 'roledene#myhotmail.onmicrosoft.com',
password: 'myPassword'
}
var ad = new ActiveDirectory(config);
var username = 'roledene#myhotmail.onmicrosoft.com';
var password = 'myPassword';
ad.authenticate(username, password, function(err, auth) {
if (err) {
console.log('ERROR: '+JSON.stringify(err));
return;
}
if (auth) {
console.log('Authenticated!');
}
else {
console.log('Authentication failed!');
}
});
but it gives the following error. what is wrong with this code ?
ERROR: {"code":"ENOTFOUND","errno":"ENOTFOUND","syscall":"getaddrinfo","hostname":"myhotmail.onmicrosoft.com","host":"myhotmail.onmicrosoft.com","port":389}
as #juunas comment, I tried with the Microsoft Graph client.
I will quote the initial step for setup the ms graph client which is exactly mentioned in here for more details
Installing ms graph client
npm install #microsoft/microsoft-graph-client
connect and query from MS graph api
const MicrosoftGraph = require("#microsoft/microsoft-graph-client");
var client = MicrosoftGraph.Client.init({
authProvider: (iss, sub, profile, accessToken, refreshToken, done) => {
done(null, {
profile,
accessToken,
refreshToken
}); //first parameter takes an error if you can't get an access token
}
});
// Example calling /me with no parameters
client
.api('/me')
.get((err, res) => {
console.log(res); // prints info about authenticated user
});

LDAP Integration Node.JS

I'm developing a simple node app using ldapjs. Unfortunately, I'm not sure how to make the connection with ldap.
Our IT department gave me the below credentials (some redacted for security).
My app.js file looks like the following. I just need to retrieve a user's data (given a username and password).
var ldap = require('ldapjs');
var client = ldap.createClient({
url: 'ldap://xx.xxx.xxx.xxxx/dc=xxxxx,dc=org'
});
var opts = {
filter: '(objectclass=user)',
scope: 'sub',
attributes: ['objectGUID']
};
client.bind('xx#xxxx.org', 'xxxx', function (err) {
console.log("Logging data...");
client.search('dc=xxxx,dc=org', function (err, search) {
search.on('searchEntry', function (entry) {
var user = entry.object;
console.log(user.objectGUID);
});
});
});
Any help is greatly appreciated. Thanks.

Node soap, consume password protected WSDL

I'm trying to build a SOAP client with Node, I'm using "soap" package (https://www.npmjs.org/package/soap) trying to consume a user/password protected WSDL.
I can't find how to pass those credentials before creating the client by "soap.createClient", and of course, I can't retrieve the WSDL if I don't provide the right credentials.
I've tried doing:
soap.security.WSSecurity('user', 'pass');
and then calling "createClient" but to no avail.
Also, I've tried to do it with the node-soap-client, with this client I (apparently) can connect to the WSDL, but after that, I've no idea where to go (how to invoke methods).
What am I doing wrong?
Thanks for all your help!
Username and password credentials can be passed like this:
var soap = require('soap');
var url = 'your WSDL url';
var auth = "Basic " + new Buffer("your username" + ":" + "your password").toString("base64");
soap.createClient(url, { wsdl_headers: {Authorization: auth} }, function(err, client) {
});
(derived from https://github.com/vpulim/node-soap/issues/56, thank you Gabriel Lucena https://github.com/glucena)
If its password protected you also need to check the correct security mechanism. I spend a day trying to figure out that the service used NTLM security(it was a clients project and I only got username and password to access the wsdl). In that case, you would need to pass the correct wsdl_options object
var wsdl_options = {
ntlm: true,
username: "your username",
password: "your password",
domain: "domain",
workstation: "workstation"
}
soap.createClient(data.credentials[data.type], {
wsdl_options
},
function(err, client) {
console.log(client.describe());
});
Also, you would need to setSecurity on the client before using any service.
the link to complete explanation: https://codecalls.com/2020/05/17/using-soap-with-node-js/
when I added the auth to the headers I still had a problem. After reading the code and a number of articles I found this to work.
// or use local wsdl if security required
let url = 'http://service.asmx?wsdl'
let wsdl = 'wsdl.wsdl';
let soap = require('soap');
let util = require('util')
soap.createClient(wsdl, function(err, client) {
//don't forget to double slash the string or else the base64 will be incorrect
client.setSecurity(new soap.BasicAuthSecurity('admin\\userName', 'password'));
client.MethodFromWSDL(args, function (err, result) {
console.log(util.inspect(result,{depth: null}))
});
});
This worked for me, the API required the auth parameters as
<UserDetails xmlns="http://url/">';
<userName>{$Username}</userName>
<password>{$Password}</password>
<program>{$program}</program>
</UserDetails>
After lots of trial and error - this ended working
const soapHeader = {
UserDetails: {
userName: process.env.userName,
password: process.env.password,
program: process.env.program
}
}
...
soap.createClient(path, function (err, client) {
if (err) {
console.log('Error creating SOAP client: ' + err);
}
client.addSoapHeader(soapHeader, "", "tns", process.env.URN);
client[process.env.FUNCTION](sargs, function (err, result, rawResponse, soapHeader, rawRequest) {
if (err) {
console.log('Error call SOAP function ' + process.env.FUNCTION + ': ', err);
}
else {
console.log(result);
}
...

Resources