Can I create an AWS Cognito user login programmatically? - authentication

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.

Related

Give web app permanent control of google email

I recently got a domain from Google Domain and it provides professional emails for the domain. So, I made a support#domain email to send and receive emails. Right now, I built a web app that will use this email to send email-verification to new users who sign up.
I got the code working, however, I used OAuth2.0 from Google to allow the web app to sign into the support email. This causes the Access token to expire and forces me to into my .env file and replace BOTH tokens. How tedious! If I were to publish this web app, I can't just go into my heroku vars and replace the tokens every hour. Thats extremely impractical.
I looked into service accounts by google, but they seem to STILL need OAuth anyways as a 3 legged OAuth. As I am using Express.js, I wanted to know if there was a way to set the tokens and be done with it permanently. Essentially giving the web app permanent control of the google account. What do I do? And what do I use? All advice is greatly appreciated.
Code for sending email verification:
const nodemailer = require("nodemailer")
const dotenv = require("dotenv")
const {generateVerifyToken} = require("./auth")
const { print } = require("#AlecRuin/color-logger")
dotenv.config()
let transporter = nodemailer.createTransport({
service:"gmail",
auth: {
type: 'OAuth2',
user: process.env.EMAIL,
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
refreshToken: process.env.REFRESH_TOKEN,
accessToken: process.env.ACCESS_TOKEN
}
})
module.exports= async function(email){
try {
let mailOptions={
from: "support#domain.us",
to:email,
subject:"Verify your email",
text:`
Thank you for signing up with redacted!!
To verify your email (and make sure you're not some kind of annoying bot), simply follow this link:
${process.env.NODE_ENV === "production"?"www.redacted.com":"localhost:3001"}/api/user/verify/?token=${generateVerifyToken(email)}
`
}
print("sending email",new Error,{isClient:false})
transporter.sendMail(mailOptions,(err,data)=>{
if (err){
console.error(err);
return err
}else{
print("Email sent!",new Error,{isClient:false})
return true
}
})
} catch (error) {
print(error,new Error, {isClient:true,severity:4})
return error
}
}

In Keystone JS v6, is there a way to store users without password being a required option?

I want to offer my users password-based authentication but also the possibility to log in with Oauth providers. I've looked into the Next-Auth adapters to get a reference for creating the schema and I'm also aware that there's an OpenSource package that adapts the createAuth method for Oauth, but it seems that the solutions provided force me to pick one of the those two.
I'm not sure how to approach this with Keystone. Should I, for example, create a Client list in the form of:
const Client = list({
fields: {
name: text({validation: {isRequired: true}}),
email: text({
validation: {isRequired: true},
isIndexed: 'unique',
isFilterable: true,
}),
password: password(),
oauthProvider: text()
}
})
that represent the clients of my app, and then a User for Admins in the form of:
const User = list({
fields: {
name: text({validation: {isRequired: true}}),
email: text({
validation: {isRequired: true},
isIndexed: 'unique',
isFilterable: true,
}),
password: password({validation: {isRequired: true}}),
}
})
the latter being the one used as a listKey for the createAuth function?
I've also thought of generating random passwords for users that Sign In with Oauth, but It feels like a liability from the security standpoint.
I'm not sure I understand the problem. You should just be able to set isRequired: false for the password field, add whatever other fields you need to store for Oauth then use one or the other.
There's no need to generate random/placeholder passwords; the Password field stores bcrypt hashes so blank/missing values will never be matched. Ie. storing null in the password field will prevent that user from authenticating with a password, it doesn't let people authenticate by submitting a blank string or anything like that.
Does that help?

Accessing secured FeatureLayer on ArcGIS online with JavaScript API

I am building a web app in a low code platform (Mendix). I am connecting the web app with ArcGIS online resources via the ArcGIS JavaScript API v4.19, which all goes pretty smoothely.
The challenge arises when I want to load specific secured ArcGIS online content via the ArcGIS JavaScript API, specifically from some FeatureLayers which are secured. I looked into the documentation and it seems the best way forward would be a so-called 'application login'. For this I want to setup an OAuth application login based on CLient ID and Client Secret. With these two I can get a valid token via AOuth and use that token to access the content by feeding the token to the IdentityManager via the JavaScript API.
This is were it goes wrong currently, I can't seem to figure out where to make it explicit on the ArcGIS online side that this specific secured FeatureLayer can be accessed via this application login, hence currently I am getting errors that the valid token and app id don't have access to the resource, being the end-point of the secured FeatureLayer.
Does anybody know how to associate a secured FeatureLayer in ArcGIS online to a application login?
EDIT 10-6-2021: Added code sample
After succesfully retrieving a valid token on the server side based on client id and client secret I use the client ID (=AppID) and token in the ArcGIS JavaScript API like below:
const token = {
server: "http://www.arcgis.com",
userId: <AppID>,
token:
<valid token retrieved via OAuth generateToken request,
ssl: true,
expires: 7200
};
IdentityManager.registerToken(token);
Only implementing this gives me an error whilst trying to access the secured feature layer:
identity-manager:not-authorized. "You are currently signed in as:
AppID. You do not have access to this resource:
https://server/someid/arcgis/rest/services/somefeatureserver/FeatureServer/0
I also read that sometimes below could be needed so added as well:
const idString = JSON.stringify(IdentityManager.toJSON());
console.debug("idString: " + idString);
IdentityManager.initialize(idString);
This resolves the error but makes a login popup appear again.
The layer is afterwards declared like below:
const layer = new FeatureLayer({
// URL to the service
url: layerObj.layerURLStatic
definitionExpression: queryDefinition,
featureReduction: clusterConfig && { type: "cluster" },
popupTemplate: {
title: "{" + inAttributeTitle + "}",
content: [
{
type: "fields", // FieldsContentElement
fieldInfos
}
],
actions: [
{
title: props.intButtonLabel,
id: btnId,
className: props.intButtonClass + intButtonIconClass,
type: "button"
}
]
},
outFields: ["*"]
});
webMap.add(layer);
Here is a snippet to generate the token and then register it with IdentityManager:
IdentityManager = require('esri/identity/IdentityManager')
function login(user, password){
var serverInfo = {
"server": "https://www.arcgis.com",
"tokenServiceUrl" : "https://www.arcgis.com/sharing/generateToken"
};
var userInfo = {
username : user,
password : password
}
IdentityManager.generateToken(serverInfo, userInfo).then(function (response){
response.server = serverInfo.server;
response.userId = user;
IdentityManager.registerToken(response);
});
}
I'm not sure how you are going to fit this in you app, but the sample should work if you paste it in your developer tools console when the app is running.
Also, it seems to me that userId property is for arcgis online username, not for appId.
As pointed out by Shaked, if you append '?token=[token_value]' int the layer URL you probably don't even need to register the token to query the layer.

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).

Meteor Accounts obtaining the SAML Response (Token / User after log in)

i have a workin SAML logon with Meteor.accounts and MS Azure. I am using this https://github.com/steffow/meteor-accounts-saml library for SAML which is derived from https://github.com/bergie/passport-saml
The procedure goes like this:
Click saml login -> popup appears
Enter user/pw data in popup -> popup closes without error
Logged in success
So now i want to get the SAML Token for further processing (or at least the information about the logged in user which meteor has taken from the IDP).
Since i dont have a clue where the SAML Token is stored by Meteor or can be fetched in the code, can someone help me getting the SAML Response?
Probably solved by now but here it goes..
According to the code the saml response is retrieved in "saml_server.js" at row 70 and the token should be in there also (loginRequest.credentialToken)
loginResult should be fairly easy to save into the Meteor.users collection
var loginResult = Accounts.saml.retrieveCredential(loginRequest.credentialToken);
var email = loginResult.profile.email;
var user = Meteor.users.findOne({username: email});
if (!user) {
Accounts.createUser({
"username": email,
"profile": StufffromloginResult
});
} else {
Meteor.users.update(
{
"username": email
},
{ "$set": {
"profile": StufffromloginResult,
}
});
}
And retrieved with:
Meteor.user().profile