Way to verify username and password of user in aws cognito using adminInitiateAuth() method - authentication

Requirement:
Below code is having 2 functions. 1st verify the username and password of user and if it is true it trigger OTP in SMS(Default behavior of AWS as 2 factor authentication is enabled). But we do not want OTP in SMS. We want OTP in Email with custom template, so implemented 2nd function with AuthFlow: 'CUSTOM_AUTH'(and 2nd method works as expected).
We do not want OTP to be triggered in SMS(But also can not disable 2 factor auth because it is used in other use cases). Also, only need solution using aws-sdk. There are ways using amplify and other library but it is not useful in case of App client secret is there.
//verify username,password and send code in sms
response0 = await cognitoIdentityServiceProvider.adminInitiateAuth({
AuthFlow: 'ADMIN_NO_SRP_AUTH',
ClientId: tenant.cognitoClientId,
UserPoolId: tenant.cognitoUserPool,
AuthParameters: {
SECRET_HASH: crypto.createHmac('SHA256', tenant.cognitoClientSecret).update(username + tenant.cognitoClientId).digest('base64'),
USERNAME: username,
PASSWORD: password
}
}).promise();
// send code to email using custom auth flow
response1 = await cognitoIdentityServiceProvider.adminInitiateAuth({
AuthFlow: 'CUSTOM_AUTH',
ClientId: tenant.cognitoClientId,
UserPoolId: tenant.cognitoUserPool,
AuthParameters: {
SECRET_HASH: crypto.createHmac('SHA256', tenant.cognitoClientSecret).update(username + tenant.cognitoClientId).digest('base64'),
USERNAME: username,
PASSWORD: tenantId + secrets.PASSWORD_SECRET
}
}).promise();
Need solution where we can check username password using AuthFlow: 'CUSTOM_AUTH'(Can change lambda triggers) or any other way where OTP should not be triggered and able to check username and password correctly.

Related

How to include TOTP MFA in AWS Cognito authentication process

I'm using Cognito user pools to authenticate my web application. I've got it all working right now but now I need to enable MFA for it. This is how I do it right now (all the code provided are server-side code):
Signing up the user:
const cognito = new AWS.CognitoIdentityServiceProvider();
cognito.signUp({
ClientId,
Username: email,
Password,
}).promise();
An email is sent to the user's address (mentioned as username in the previous function call) with a code inside.
The user reads the code and provides the code to the next function call:
cognito.confirmSignUp({
ClientId,
ConfirmationCode,
Username: email,
ForceAliasCreation: false,
}).promise();
The user logs in:
const tokens = await cognito.adminInitiateAuth({
AuthFlow: 'ADMIN_NO_SRP_AUTH',
ClientId,
UserPoolId,
AuthParameters: {
'USERNAME': email,
'PASSWORD': password,
},
}).promise();
I'm pretty happy with this process. But now I need to add the TOTP MFA functionality to this. Can someone tell me how these steps will be changed if I want to do so? BTW, I know that TOTP MFA needs to be enabled for the user pool while creating it. I'm just asking about how it affects my sign-up/log-in process.
Alright, I found a way to do this myself. I must say, I couldn't find any documentation on this so, use it at your own risk!
Of course, this process assumes you have a user pool with MFA enabled (I used the TOTP MFA).
Signing up the user:
const cognito = new AWS.CognitoIdentityServiceProvider();
cognito.signUp({
ClientId,
Username: email,
Password,
}).promise();
An email is sent to the user's address (mentioned as username in the previous function call) with a code inside.
The user reads the code and provides the code to the next function call:
cognito.confirmSignUp({
ClientId,
ConfirmationCode: code,
Username: email,
ForceAliasCreation: false,
}).promise();
The first log in:
await cognito.adminInitiateAuth({
AuthFlow: 'ADMIN_NO_SRP_AUTH',
ClientId,
UserPoolId,
AuthParameters: {
'USERNAME': email,
'PASSWORD': password,
},
}).promise();
At this point, the return value will be different (compared to what you'll get if the MFA is not enforced). The return value will be something like:
{
"ChallengeName": "MFA_SETUP",
"Session": "...",
"ChallengeParameters": {
"MFAS_CAN_SETUP": "[\"SOFTWARE_TOKEN_MFA\"]",
"USER_ID_FOR_SRP": "..."
}
}
The returned object is saying that the user needs to follow the MFA_SETUP challenge before they can log in (this happens once per user registration).
Enable the TOTP MFA for the user:
cognito.associateSoftwareToken({
Session,
}).promise();
The previous call is needed because there are two options and by issuing the given call, you are telling Cognito that you want your user to enable TOTP MFA (instead of SMS MFA). The Session input is the one return by the previous function call. Now, this time it will return this value:
{
"SecretCode": "...",
"Session": "..."
}
The user must take the given SecretCode and enter it into an app like "Google Authenticator". Once added, the app will start showing a 6 digit number which is refreshed every minute.
Verify the authenticator app:
cognito.verifySoftwareToken({
UserCode: '123456',
Session,
}).promise()
The Session input will be the string returned in step 5 and UserCode is the 6 digits shown on the authenticator app at the moment. If this is done successfully, you'll get this return value:
{
"Status": "SUCCESS",
"Session": "..."
}
I didn't find any use for the session returned by this object. Now, the sign-up process is completed and the user can log in.
The actual log in (which happens every time the users want to authenticate themselves):
await cognito.adminInitiateAuth({
AuthFlow: 'ADMIN_NO_SRP_AUTH',
ClientId,
UserPoolId,
AuthParameters: {
'USERNAME': email,
'PASSWORD': password,
},
}).promise();
Of course, this was identical to step 4. But its returned value is different:
{
"ChallengeName": "SOFTWARE_TOKEN_MFA",
"Session": "...",
"ChallengeParameters": {
"USER_ID_FOR_SRP": "..."
}
}
This is telling you that in order to complete the login process, you need to follow the SOFTWARE_TOKEN_MFA challenge process.
Complete the login process by providing the MFA:
cognito.adminRespondToAuthChallenge({
ChallengeName: "SOFTWARE_TOKEN_MFA",
ClientId,
UserPoolId,
ChallengeResponses: {
"USERNAME": config.username,
"SOFTWARE_TOKEN_MFA_CODE": mfa,
},
Session,
}).promise()
The Session input is the one returned by step 8 and mfa is the 6 digits that need be read from the authenticator app. Once you call the function, it will return the tokens:
{
"ChallengeParameters": {},
"AuthenticationResult": {
"AccessToken": "...",
"ExpiresIn": 3600,
"TokenType": "Bearer",
"RefreshToken": "...",
"IdToken": "..."
}
}

Authentification with ldap without user's password

I am trying to create login authentication with ldap js. I set up all Credentials and everything is working fine, but the problem is I can bind a user just with his Uid (user id aka username), it didn't ask for a password and I don't know how to fix this it must ask for Uid and userPAssword to connect
I tried to connect to with the same credentials including userPassword but it didn't work for me
ldapConfig.js
in this file i set up all ldap config
'url': 'ldap://*************',
'port': '***',
'timeout': '',
'connectTimeout': '',
'secret': '**********',
'reconnect': true,
'filtre': '(&(ObjectClass=*******)',
'search_dn': 'ou=******,dc=****,dc=****',
'domain': 'cn=******,dc=****,dc=****'
login.js
in this file i tried to connect to ldap server and it work realy fine and then i want to get user by uid
const server = ldapConfig.url
const ldapDomain = ldapConfig.domain
const password = ldapConfig.secret
const searchDomain = ldapConfig.search_dn
const client = ldap.createClient({
url: server
})
client.bind(ldapDomain, password, err => {
assert.ifError(err)
})
const opts = {
scope: 'sub',
filter: ldapConfig.filtre + `(mail=${request.body.mail}))`
}
client.search(searchDomain, opts, (err, res) => {
assert.ifError(err)
res.on('searchEntry', entry => {
console.log(entry.object)
} )
I hope it's clear . Thanks
Unauthenticated bind (a seemingly successful bind when you supply a userID and null password) may be enabled in your directory. If you are using OpenLDAP, as the quesstion tags indicate, check slapd.conf for allow bind_anon_cred.
Unless there is a specific need for unauthenticated bind, I disable it on the directory servers. In the rare cases where unauthenticated bind is required, all applications authenticating against the directory need to validate user input before attempting to bind -- that is, verify that the input username and password values are not null.

auth0 - email verification - user account does not exist or verification code is invalid

Here is my problem : In auth0 dashboard, I select a user within my users list and click on send a verification email... The user receive the mail, click on the link and get an error "User account doesn't exist or verification code is invalid" But the user exists and I do not use passwordless or sms authentication , my users have to enter their password and are also stored in mongodb. Any ideas to solve this?
-- edited precision added --
#Arcseldon
I'am actually using a customDB and here is my getUser script, but I don't know what to change, could you help me?
Thank you!
function getByEmail (email, callback) {
mongo('mongodb://user:pass#dsXXXX.mlab.com:XXXX/base', function (db) {
var users = db.collection('user');
users.findOne({ email: email }, function (err, user) {
if (err) return callback(new Error("my error message"));
if (!user) return callback(null);
var profile = {
user_id: user._id,
nickname: user.username,
email: user.email,
};
callback(null, profile);
});
});
}
Ok, just re-read your question - where you state "my users have to enter their password and are also stored in mongodb." - are you referring to your own Mongo DB? Are you using an Auth0 Custom DB Connection? Confusingly, Auth0 also uses MongoDB for its own DB storage, hence the clarification. If you are using a Custom DB connection to your own DB, then this may be a misconfiguration of one of your Custom DB Scripts. If using Custom DB Script, please double-check the implementation of your GetUser.js script.
In the event, you are using an Auth0 DB (not a custom DB) then definitely check with Auth0 support team (as per comment and your reply above).

Can I create an AWS Cognito user login programmatically?

I would like my app to allow users with a Facebook, Google, Amazon... etc... accounts to be able to login to my app. This works fine through AWS Cognito.
However, is there a way for the app to create a user login programmatically if the user does not have any of those logins?
The user would provide an id and a password and the app would send the information to the authentiation provider to create a new login/account.
I would not need to implement my own authentication mechanism and worry about how the passwords are stored, etc.
From my research I take that there is no way to do this with existing authentication providers or even other services such as OpenID.
Do you have any other options if I do not want to implement my own login storage and authentication? It would not necessarily need to integrate with AWS Cognito.
I'm a little confused by your question. If you're asking:
Can I create new usernames and passwords on Facebook / Google programatically?
Then the answer is no. You have to sign up for Facebook / Google on their site. If you're asking:
Can I create a new user with a username and password that only exists in Cognito?
Then the answer is yes. To do this, it depends on whether you're creating the user in a browser or on a server. In a browser, use the Cognito Javascript API. On a server, use the Cognito Admin Server APIs.
Here's some sample code for creating a new user on the server in Node JS (replace my strings with your own tokens, especially the ones with # signs in them):
let params = {
UserPoolId: "#cognito_pool_id#",
Username: "jhancock",
DesiredDeliveryMediums: ["EMAIL"],
ForceAliasCreation: false,
MessageAction: "SUPPRESS",
TemporaryPassword: "somePassword",
UserAttributes: [
{ Name: "given_name", Value: "John"},
{ Name: "family_name", Value: "Hancock"},
{ Name: "name", Value: "John Hancock"},
{ Name: "email", Value: "john#gmail.com"},
{ Name: "phone_number", Value: "+15125551212"}
],
};
console.log("Sending params to cognito: " + JSON.stringify(params));
let cognitoIdentityServiceProvider = new AWS.CognitoIdentityServiceProvider({region: "us-east-1"});
cognitoIdentityServiceProvider.adminCreateUser(params, function(error, data) {
if (error) {
console.log("Error adding user to cognito: " + JSON.stringify(error), error.stack);
} else {
console.log("Received back from cognito: " + JSON.stringify(data));
}
}
One you get that working, you'll probably want to see this post about how to change the temporary password into a real one.
Hi from my previous experence in implementing of the social media authentication.
I would conclude that it is quite hard to implement.If you do not what to show web view to authenticate user in iOS you need to use iOS ACAccountStore class for this, but even this only gives opportunity to log in not to sign in.

Auth between a website and self-owned API

This has probably been asked before, so a preemptive apology from me.
I built a site and I built an API. The API will also be used by a mobile app in the future. I own both so I'm pretty sure two and three legged OAuth aren't for me. The API has parts that are accessible to the world and other parts that are protected and require a user account. To keep things simple I've just gone with a https + Basic Auth solution (for now). It's all fine and good when testing requests manually to the API (I didn't write tests because I'm a bad person), things work as expected and Basic Auth is fine.
I'm trying to solve the flow of a user logging in with plaintext user and password, send that to the API to authenticate, the API just needs to say yes or no, yet all requests from the site (on behalf of a user) to the API should be signed in some way with their credentials for when they want to POST/GET/PUT/DEL one of the protected resources.
Out of all of the auth resources I've read I'm still confused as to what scheme to use. Storing the plaintext password on the site side so that I can base 64 encode it and send it over the wire seems bad, but it looks like that's what I'd have to do. I've read of digest auth but I'm not sure I get it. Any and all advice is welcome.
This is how I would handle this case;
POST the username and password as a plain text to your api using HTTPS of course.
Then validate it to your database, the best algorithm used nowadays to salt password is bcrypt.
If the user is not valid return 401, or whatever.
If the user is valid, return a JWT token with his profile signed with a Public Key algorithm.
Your fron-end knows the public key so it can decode the JWT but it can't generate a new one.
For every request that needs authentication, you attach an Authentication header, with Bearer [JWT]
A middleware in the backend reads this header and validate it with the private key.
Don't be affraid of JWT there are plenty of implementations for every language and framework and is easier than you might think. A lot of applications are already using JWT already even Google.
Auth0 is an authentication broker that can validate against any identity provider or custom database, and returns JWTs. It provides a clientID that can be used to decode the profile in the front end and a secret to validate the tokens in the backend as well as client side library to do this.
Disclaimer: I work for auth0.
Update: Since you mention node.js and express in comments I will give an example in this technology.
var http = require('http');
var express = require('express');
var jwt = require('jsonwebtoken'); //https://npmjs.org/package/node-jsonwebtoken
var expressJwt = require('express-jwt'); //https://npmjs.org/package/express-jwt
var secret = "this is the secret secret secret 12356";
var app = express();
app.configure(function () {
this.use(express.urlencoded());
this.use(express.json());
this.use('/api', expressJwt({secret: secret}));
});
//authentication endpoint
app.post('/authenticate', function (req, res) {
//validate req.body.username and req.body.password
//if is invalid, return 401
var profile = {
first_name: 'John',
last_name: 'Foo',
email: 'foo#bar.com',
id: 123
};
var token = jwt.sign(profile, secret, {
expiresInMinutes: 60*5
});
res.json({
token: token
});
});
//protected api
app.get('/api/something', function (req, res) {
console.log('user ' + req.user.email + ' is calling /something');
res.json({
name: 'foo'
});
});
//sample page
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
http.createServer(app).listen(8080, function () {
console.log('listening on http://localhost:8080');
});
This is an express application with one endpoint that validates username and password. If the credentials are valid it returns a JWT token with the full profile, with expiration 5 hours.
Then we have an example endpoint in /api/something but since I've a express-jwt middleware for everything on /api it requires a Authorization: Bearer header with a valid token. The middleware not only validates the token but also parses the profile and put it on req.user.
How to use this client-side? This is an example with jquery:
//this is used to parse the profile
function url_base64_decode(str) {
var output = str.replace("-", "+").replace("_", "/");
switch (output.length % 4) {
case 0:
break;
case 2:
output += "==";
break;
case 3:
output += "=";
break;
default:
throw "Illegal base64url string!";
}
return window.atob(output); //polifyll https://github.com/davidchambers/Base64.js
}
var token;
//authenticate at some point in your page
$(function () {
$.ajax({
url: '/authenticate',
type: 'POST',
data: {
username: 'john',
password: 'foo'
}
}).done(function (authResult) {
token = authResult.token;
var encoded = token.split('.')[1];
var profile = JSON.parse(url_base64_decode(encoded));
alert('Hello ' + profile.first_name + ' ' + profile.last_name);
});
});
//send the authorization header with token on every call to the api
$.ajaxSetup({
beforeSend: function(xhr) {
if (!token) return;
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
}
});
//api call
setTimeout(function () {
$.ajax({
url: '/api/something',
}).done(function (res) {
console.log(rest);
});
}, 5000);
First, I've an authenticate call with the username and password, I can decode the profile in the JWT to get the user profile and I also save the token to use in every request later on.
The ajaxSetup/beforeSend trick adds the header for every call. So, then I can make a request to /api/something.
As you can imagine this approach doesn't use cookies and sessions so it works out of the box in CORS scenarios.
I'm a big fan of passport.js and I've contributed a lot of adapters and fixes for some other adapter but for this particular case I wouldn't use it.
I've been thinking about a similar scenario lately; here's what I did:
SSL + Basic Auth
In the DB (on the API side), generate a random salt (per user), and save the salt and the hashed (password + salt). When a request arrives, throw on the salt and hash it, then compare to what you've saved
Send the password in plaintext - you are using SSL so I think this is okay (this is the part I am most uncertain of)
I don't have a great reason for recommending this but in case you have a reason to use it:
.4. Attach a timestamp to every request and have them expire after a couple of minutes.
The reason you should save salted-and-hashed passwords in your DB is in case someone steals your DB.
Basically I'm putting a lot of faith into SSL, and what I've read tells me that's okay.