ldap Invalid Credentials While Authenticating User(NodeJs) - node.js

There are two Active Directory (LDAP Servers). Following are the users which belongs to their servers respectively.
Server user password
1- abc.pk user_abc#abc.pk ********
2- xyz.com.pk user_xyz#xyz.com.pk ********
I am authenticating the user in NodeJS with library (ActiveDirectory). Below is my code where I am authenticating user_xyz#xyz.com.pk from its respective server.
const ActiveDirectory = require('activedirectory');
var ad = new ActiveDirectory({
"url": "ldap://xyz.com.pk",
"baseDN": "DC=xyz,DC=com,DC=pk"
});
ad.authenticate(username, password, function(err, auth) {
console.log('auth function called with username: '+username);
if (err) {
console.log('auth function called and with following err '+JSON.stringify(err));
return;
}
if (auth) {
console.log('Authenticated from Active directory!');
});
it works fine. Same works fine if I authenticate user_abc#abc.pk from server 1 by updating the url and baseDN.
var ad = new ActiveDirectory({
"url": "ldap://abc.pk",
"baseDN": "DC=abc,DC=pk"
});
Server abc.pk has Trust Relations with Server xyz.com.pk. Means I have to authenticate the user user_abc#abc.pk from the Server xyz.com.pk . using the following configurations.
var ad = new ActiveDirectory({
"url": "ldap://xyz.com.pk",
"baseDN": "DC=xyz,DC=com,DC=pk"
});
but now facing the error of invalid credentials. This is the exact error I am facing {"lde_message":"80090308: LdapErr: DSID-0C090453, comment: AcceptSecurityContext error, data 52e, v3839\u0000","lde_dn":null}
If I authenticate the user_abc#abc.pk from xyz.com.pk Server with Active Directory Explorer it works fine.
Active Directory Explorer image
It would be a great help if someone could give me a solution.
Thanks

I solved the problem by checking the following 2 things:
1.-The configuration must be separated in the baseDN part:
var config = {
url: 'ldap://aaa.bbb.ccc.ddd',
baseDN: 'DC=aaa,DC=bbb,DC=ccc,DC=ddd'
};
2.-It seems the problem is not from code https://community.arubanetworks.com/community-home/digestviewer/viewthread?MID=40296#:~:text=%22AcceptSecurityContext%20error%2C%20data%2052e%22,instead%20of%20just%20the%20username.
According to the post, sometimes the domain name server may be required for authentication. It would be necessary to verify if it works with "username" or "username#aaa.bbb.ccc.ddd" or "aaa.bbb.ccc.ddd\username" depending on how the user is registered.
I hope my experience can be of use. Cheers

Related

Need help: AADSTS700016: Application with identifier was not found in the directory Azure Account AD?

My request for an Azure AD Oauth2 token works fine when I run my node.js app on a VM on Azure. It's making the request using another team's client id/secret because further down in the code, the program will make REST APIs calls to their services using that token. The program gets an error after fetching/requesting a token if my program (node.js app) is launched from a Github workflow. (The workflow worked successfully three times before getting this error. The error occurs every time now.) Thank you for your help! It's much appreciated and I don't have much experience in this area.
async function getToken(config) {
const params = new URLSearchParams()
params.append('grant_type', 'client_credentials')
params.append('client_id', config.clientId)
params.append('client_secret', config.clientSecret)
params.append('scope', config.scopeUrl)
//url = https://login.microsoftonline.com/{{AD.tenantId}}/oauth2/v2.0/token
const response = await fetch(config.tokenRequestUrl, { method: 'POST', body: params })
const jsonObj = await response.json()
console.log('!!!!JSON='+JSON.stringify(jsonObj))
if ((typeof jsonObj.access_token !== 'undefined') && (jsonObj.access_token != null)) {
return jsonObj.access_token
} else {
return null
}
}
Output:
!!!!3S0N=***"error":"unauthorizedclient","errordescription":"AADSTS700016: Application with identifier '***' was not found in the directory 'xxxxx Azure Account AD'. This can happen if the application has
not been installed by the administrator of the tenant or consented to by any user in the tenant. You may have sent your authentication request to the wrong tenant.***
I figured it out! The Github workflow was using the wrong client id/secret.

ServerError: AADSTS50058: A silent sign-in request was sent but none of the currently signed in user(s) match the requested login hint"

SSO fails "ServerError: AADSTS50058: A silent sign-in request was sent but none of the currently signed in user(s) match the requested login hint"
when I use same account for both work and personal azure account.
I have 2 AAD accounts (one is with my work account and the other one is personal account but both attached with same email and both are using same credentials). When I use msal.js library for single sign on application. It takes me to my work account where it asks me to validate the credentials (using standard pop up dialog) by giving full email address and does not authenticate properly even if give right credentials. As I need to login using my personal account
I expect this should validate using my ad alias#company.com credentials. I tried with different account option in the dialog, but it fails and shows up same full email account.
How can I use my adalias#company.com as a default user id?
Here are the piece of the code I am trying to use.
var msalConfig = {
auth: {
clientId: 'xxxxxxxxxx', // This is your client ID
authority: "https://login.microsoftonline.com/{tenantid}" // This is tenant info
},
cache: {
cacheLocation: "localStorage",
storeAuthStateInCookie: true
}
};
var graphConfig = {
graphMeEndpoint: "https://graph.microsoft.com/v1.0/me"
};
var requestObj = {scopes: ["user.read", "email"]};
// Is there a way to change here to get the required user id?
var myMSALObj = new Msal.UserAgentApplication(msalConfig);
// Register Callbacks for redirect flow
myMSALObj.handleRedirectCallbacks(acquireTokenRedirectCallBack,
acquireTokenErrorRedirectCallBack);
myMSALObj.handleRedirectCallback(authRedirectCallBack);
function signIn() {
myMSALObj.loginRedirect(requestObj).then(function (loginResponse) {
// Successful login
acquireTokenPopupAndCallMSGraph();
}).catch(function (error) {
// Please check the console for errors
console.log(error);
});
}
Here is the error message I get:
ServerError: AADSTS50058: A silent sign-in request was sent but none of the
currently signed in user(s) match the requested login hint
The expected result is seamless login to other application.
If you want to provide a login_hint to indicate the user you are trying to authenticate try:
var requestObj = {scopes: ["user.read", "email"], loginHint: "adalias#company.com"};
Reference https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/FAQs#q10-how-to-pass-custom-state-parameter-value-in-msaljs-authentication-request-for-example-when-you-want-to-pass-the-page-the-user-is-on-or-custom-info-to-your-redirect-uri

Authentication with Active Directory using sAMAccountName and password / NodeJs

I m trying to authenticate to a server with Active Directory using Nodejs. I read a lot a of answers of that but no body use the sAMAccountName as attribute to do that.
My code is :
let ActiveDirectory = require('activedirectory');
let config = {
url: 'ldap://XX.XX.XX.XXX:389',
baseDN: 'DC=domain,DC=com',
username: 'serverUserName',
password: 'serverPsw'
};
let ad = new ActiveDirectory(config);
let username = 'sAMAccountName=11111111111, OU=Usuarios, DC=domain,DC=com',
password = 'myPassword';
ad.authenticate(username, password, function (err, auth) {
if (err) {
console.log('ERROR: ' + JSON.stringify(err));
return;
}
if (auth) {
console.log('\nAuthenticated!', auth);
}
else {
console.log('\nAuthentication failed!');
}
});
This code only works if a change the username
'CN=myIdentifier,OU=Usuarios,DC=domain,DC=com'
and use the CN as attribute.
I really don't have idea what to do but it must work using the sAMAccountName.
Can anybody give me a help of how to make it work?
Thanks
You can authenticate against Active directory LDAP using sAMAccountName if you include the domain too - like company\logonid instead of just login ID. You can also use the full userPrincipalName like logonid#company.ccTLD
With either of those formats, you do not use any of the LDAP syntax components (something= or the ,ou=xyz,dc=abc). You use just the login ID and domain name (in the example above, the legacy style domain name is company and the AD style domain name is company.ccTLD)

Accessing Skype for Business API (UCWA) : HTTP 403 / Forbidden

I'm trying to connect to & use Skype for Business API (UCWA) following this procedure, using a Node.js test script.
I've registered a test app in Azure AD and checked all permissions concerning Skype for Business Online.
I'm doing this (simplified):
var adal = require('adal-node');
var https = require('https');
var clientId = 'a5cbbd......cc4a1'; // = app ID
var clientSecret = 'IOSDk1......LJ6vE=' // test key from Azure AD
var context = new adal.AuthenticationContext('https://login.windows.net');
// 'Autodiscover' step
// (callRestAPI() makes an HTTPS request using https.request() and returns results as JSON)
callRestAPI('webdir.online.lync.com', 443, '/autodiscover/autodiscoverservice.svc/root', 'GET', null /* no specific headers */, function(err, res) {
if (err) { console.log(err); return err; }
// extract discovered domain (I get something like https://webdir1e.online.lync.com)
let regex = new RegExp('^(https?://[^/]*)', 'g');
let sfbDiscoveredDomain = regex.exec(response._links.user.href);
sfbDiscoveredDomain = sfbDiscoveredDomain[1];
// 'Acquire token' step
context.acquireTokenWithClientCredentials(sfbDiscoveredDomain, clientId, clientSecret, function(err, res) {
if (err) { console.log(err); return err; }
regex = new RegExp('^https?://([^/]*)', 'g');
let sfbHost = regex.exec(res.resource);
sfbHost = sfbHost[1]; // here I get something like 'webdir1e.online.lync.com'
// 'Resending an autodiscovery request with the bearer token' step
callRestApi(sfbHost, 443, '/autodiscover/autodiscoverservice.svc/root/oauth/user', 'GET', {'Authorization': 'Bearer '+res.accessToken}, function(err, res) {
if (err) { console.log(err); return err; }
console.log(res);
});
});
});
The last step (resending an autodiscovery request) always fails with error HTTP 403/Forbidden.
There is an additional interesting response header:
'x-ms-diagnostics': '28070;source="AM41E00EDG01.infra.lync.com";reason="Service does not allow a cross domain request from this origin."'
...but I still don't understand why this error occurs.
I've played with additional headers seen here and there in various code samples (X-Ms-Origin and Host), with no luck.
This issue (Service does not allow a cross domain request from this origin.) is mostly caused by the "Cross-Origin Resource Sharing (CORS)" and that the address which is requesting the access isn´t "whitelisted".
An Skype for Business Administrator can configure that via (more info's here) when the server is on premises (see StackOverflow question here):
$x = New-CsWebOrigin -Url "https://apps.contoso.com"
Set-CsWebServiceConfiguration -Identity "{YOUR_IDENTITY}" -CrossDomainAuthorizationList #{Add=$x}
However as your Skype for Business isn´t on premises (its online) I assume there is nothing you can do as this section is mostly controlled by the cloud admins from Microsoft.
However as UCWA is supported with Skype for Business online I assume there is something wrong on your side. Did you checked if the application is correctly registered as explained here? If yes a fiddler trace might be useful to see what caused that issue.

Accessing Office365 API with Client Credentials Flow

I am trying to develop a node application that would be able to access my Outlook.com mails.
I am trying to do it in a way it doens't require me to enter my credentials, the application will know them (user name and password). I am not too worried about storing them in the config of my application.
I am using simple-oauth2 but I keep getting an error. The following is the code that is trying to retrieve the Oauth token:
const credentials = {
client: {
id: this.appId,
secret: this.appSecret,
},
auth: {
tokenHost: "https://login.microsoftonline.com",
authorizePath: "common/oauth2/v2.0/authorize",
tokenPath: "common/oauth2/v2.0/token",
},
};
const oathClient = oauth2.create(credentials);
const tokenConfig = {
username: "zzz#outlook.com",
password: "xxxxx",
scope: "Mail.Read",
};
const result = await oathClient.ownerPassword.getToken(tokenConfig);
const token = oathClient.accessToken.create(result);
However when calling get token I get the following response:
"error": "invalid_grant",
"error_description": "AADSTS70000: The grant is not supported by this API version\r\nTrace ID: 91935472-5d7b-4210-9a56-341fbda12a00\r\nCorrelation ID: 6b075f4e-b649-493e-a87b-c74f0e427b47\r\nTimestamp: 2017-08-19 14:00:33Z",
"error_codes": [ 70000],
I have aded the application in apps.dev.microsoft.com
Added a platform (Web API) for it.
Added the "Mail.Read" permission on Microsoft Grah
And I am using the apikey and secret I generated there.
Googling looks like all the examples I find are to connect is using a client certificate. Is it possible to use the API using the API credentials?
If the only way is using certificates, is there a way I can use simple-oauth2 for that?
Ok, looks like I was using the wrong method.
Trying to access using the ClientCredentials module on simple-ouath2 and its workign now:
const tokenConfig = {
scope: "https://graph.microsoft.com/.default",
};
const result = await oathClient.clientCredentials.getToken(tokenConfig);

Resources