AWS Cognito Auth with Phone Number OTP just like firebase, without Amplify - javascript

I am trying to enable login & Sign Up with Phone Number + OTP for a website (not Mobile) just like Firebase Auth offers.
I have looked up endless tutorials, almost all of which require AWS Amplify, which then requires knowing React/Angular/Vue (I'm not a front end developer). I followed tutorials like this one (https://techinscribed.com/passwordless-phone-number-authentication-using-aws-amplify-cognito/) and have created all the Lambda Functions, Cognito UserPools as stated in the tutorial. My roadblock is that it requires Amplify, and I just want to use vanilla JavaScript.
So I downloaded the AWS SDK builder with:
AWS.CognitoIdentity
AWS.CognitoIdentityServiceProvider
AWS.CognitoSync
I am using Zappa with Flask (serverless) to render HTML + JS to the user. I have everything else configured with API Gateway for the backend. All I need to do is authenticate users and generate sessions tokens for authenticated users, allowing access to their personal data, (like saved info, favorites, etc).
I am praying for someone to help me figure out how I can authenticate my users and generate the session/JWT tokens for my users. Any guidance would be appreciated.

AWS Amplify is just a wrapper around the core AWS services. The goal is to provide a boilerplate that takes care of the common access patterns. You don't have to use framework if you don't want to and can use the core services directly.
Before I point you to these low level APIs, it's worth noting that Amplify does have vanilla JS APIs as well. Refer the official docs here. You can handle authentication with only JS and not worry about any frameworks.
The docs for the Authentication module can be found here.
For reference, here are the scripts for Sign-up and login:
import { Auth } from 'aws-amplify';
async function signUp() {
try {
const user = await Auth.signUp({
username,
password,
attributes: {
email, // optional
phone_number, // optional - E.164 number convention
// other custom attributes
}
});
console.log({ user });
} catch (error) {
console.log('error signing up:', error);
}
}
async function SignIn() {
try {
const user = await Auth.signIn(username, password);
} catch (error) {
console.log('error signing in', error);
}
}

Cotter co-founder here.
We have a simple library that allows you to send OTP verification to users via SMS/WhatsApp with Vanilla Javascript.
Guide: Sending OTP with HTML + Vanilla JS.
Working Example: in CodeSandbox (you need to add your API_KEY_ID, which you can get from the dashboard).
1. Import the library
<!-- 1️⃣ Get Cotter SDK -->
<script
src="https://js.cotter.app/lib/cotter.js"
type="text/javascript"
></script>
2. Make a div with id="cotter-form-container" to contain the form
<div
id="cotter-form-container"
style="width: 300px; height: 300px;"
></div>
3. Show the form
<!-- 3️⃣ Initialize Cotter with some config -->
<script>
var cotter = new Cotter("<YOUR_API_KEY_ID>"); // 👈 Specify your API KEY ID here
cotter
.signInWithOTP()
.showPhoneForm() // to send OTP to using email use .showEmailForm()
.then(payload => console.log(payload))
.catch(err => console.log(err));
</script>
4. Get JWT Tokens
Check your console logs, you should get a response like this:
{
"token": {...},
"phone": "+12345678910",
"oauth_token": {
"access_token": "eyJhbGciOiJFUzI1NiIsImtpZCI6I...", // use this
"id_token": "eyJhbGciOiJFUzI1NiIsImtpZCI6IlN...",
"refresh_token": "27322:UYO4pcA17i4sCIYD...",
"expires_in": 3600,
"token_type": "Bearer",
"auth_method": "OTP"
},
"user": {
"ID": "abcdefgh-abcd-abcd-abcd-f17786ed499e", // Cotter User ID
... // more user info
}
}
Use the oauth_token.access_token for your sessions, here's how you can validate the JWT token.
5. Customize form
To show buttons to send the OTP via both SMS and WhatsApp, go to Dashboard > Branding.

Related

Ionic 5 IOS & Stripe Payment Request Button - Stripe.js integrations must use HTTPS

I'm trying to add a Payment Request Button to my Ionic 5 app. However, no matter how I run the app, I always get the following message and the button won't show.
[warn] - You may test your Stripe.js integration over HTTP. However,
live Stripe.js integrations must use HTTPS.
I'm loading the Stripe API over https
<script src="https://js.stripe.com/v3/"></script>
I've imported it in to my page
declare var Stripe;
// Check the availability of the Payment Request API first.
const prButton = elements.create('paymentRequestButton', {
paymentRequest,
});
paymentRequest.canMakePayment().then(result => {
if (result) {
prButton.mount('#payment-request-button');
} else {
document.getElementById('payment-request-button').style.display = 'none';
}
);
I've tried running it in Safari on Mac (running with --ssl and a valid certificate), Xcode Emulator, A Real iPhone and the result is always the same.
Also worth noting is that I'm using Capacitor, not Cordova. I've tried this in my capacitor.config.json but it had no effect.
"iosScheme": "https",
Update:
So it turns out that it's because the app runs with the local urlScheme of capacitor:// rather than https:// and the development team at Ionic currently have no plans to rectify this. Is there any way to make the Payment Request Button appear in a non-https environment?
After a lot of back and forth with Stripe's support team, I finally came up with a solution. A lot of what they said is included in this answer (placed in blockquotes). I've also included a code example that will hopefully help make sense of it.
I'm absolutely aware this is quite complex but unfortunately when not
using our official iOS SDK the process is quite involved, and as of
right now we don't have any official support for cross-platform
technologies like Ionic or React Native.
You must have an apple developer account, a merchant id and have a payment processing certificate uploaded to stripe (see steps 1->3 of https://stripe.com/docs/apple-pay#native)
You can use the cordova plugin (https://github.com/samkelleher/cordova-plugin-applepay#example-response) to generate an apple pay token. This will then be submitted to the V1 stripe API and exchanged for a Stripe Token. This is how Stripe's official IOS SDK works by tokenizing the PKPayment object in to a Stripe Token.
The paramaters to pass to the end point (not in the documentation) are;
pk_token (the string that you get from base64 decoding the
paymentData)
pk_token_payment_netowrk (paymentMethodNetwork)
pk_token_instrument_name (paymentMethodDisplayName)
pk_token_transaction_id (transactionIdentifier)
The names in the brackets are what is returned when using the cordova plugin.
Once you call this endpoint, you should get back a standard Stripe
token object(but the request will fail if you haven't registered your
Apple Pay payment processing cert as mentioned above). The Stripe
token(tok_xxx) can be used for payments as normal — the easiest way is
to convert it to a PaymentMethod by calling /v1/payment_methods with
type=card&card[token]=tok_xxxx , and then using it to confirm a
PaymentIntent.
Code Example
completeApplePay(resp){
const _this = this;
return new Promise((resolution, rejection) => {
$.post({
url: 'https://api.stripe.com/v1/tokens',
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer pk_test_xxxxxxxxxxxxxxxx")
},
data: {
pk_token: atob(resp.paymentData),
pk_token_payment_network: resp.paymentMethodNetwork,
pk_token_instrument_name: resp.paymentMethodDisplayName,
pk_token_transaction_id: resp.transactionIdentifier
},
success: function (data) {
resolution({
token: data.id
});
}
});
});
}
The (resp) parameter in the function above is the response from the cordova plugin;
const applePayTransaction = await this.applePayController.makePaymentRequest(order).then(resp => {
this.stripe.completeApplePay(resp).then((stresp:any) => {
// code goes here to store order in database etc
})
});
await this.applePayController.completeLastTransaction('success');

Silent authentication for own website inside tab of custom Teams app

After two months of experimenting with Teams Authentication via adal.js and msal.js and failure, I’m close to giving up. So I really need your help.
Basically I need to “silently” authenticate the logged in Teams User for my own website (tab) inside my app that I created with App Studio. The reason for that is, so that I can use the data of the authentication token for the login of my own website.
So far I was only able to get this working with msal.js and a popup, which according to Teams developer I’ve asked is not the way to go. Understandable, since I cannot use the popup method on the Teams Client because it gets blocked.
I’ve tried this silent login method (https://github.com/OfficeDev/microsoft-teams-sample-complete-node/blob/master/src/views/tab-auth/silent.hbs) that was recommend to me.
Sadly it didn’t work. All I get is a “Renewal failed: Token renewal operation failed due to timeout” error.
Since the msal.js popup variant (Node.js Azure Quick Start Example) I used before worked in a web browser, I don’t think that the configuration of Azure App is wrong.
This is my code so far:
// onLoad="prepareForm()"
<!--- Import package for authentication information in Teams/Azure--->
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.15/js/adal.min.js" integrity="sha384-lIk8T3uMxKqXQVVfFbiw0K/Nq+kt1P3NtGt/pNexiDby2rKU6xnDY8p16gIwKqgI" crossorigin="anonymous"></script>
<script src="https://statics.teams.microsoft.com/sdk/v1.4.2/js/MicrosoftTeams.min.js" crossorigin="anonymous"></script>
<script language="JavaScript">
let config = {
clientId: "1402f497-d6e8-6740-9412-e12def41c451", // I've changed it for this stackoverflow post
redirectUri: "https://myredirect.com", // I've changed it for this stackoverflow post
cacheLocation: "localStorage",
navigateToLoginRequestUrl: false,
};
microsoftTeams.initialize()
/// START Functions for Teams
function getTeamsContext() {
microsoftTeams.getContext(function(context) {
startAuthentication(context);
});
}
function startAuthentication(teamsContext) {
if (teamsContext.loginHint) {
config.extraQueryParameters = "scope=openid+profile&login_hint=" + encodeURIComponent(teamsContext.loginHint);
} else {
config.extraQueryParameters = "scope=openid+profile";
}
let authContext = new AuthenticationContext(config);
user = authContext.getCachedUser();
if (user) {
if (user.profile.oid !== teamsContext.userObjectId) {
authContext.clearCache();
}
}
let token = authContext.getCachedToken(config.clientId);
if (token) {
console.log(token)
// Get content of token
} else {
// No token, or token is expired
authContext._renewIdToken(function (err, idToken) {
if (err) {
console.log("Renewal failed: " + err);
// Some way of logging in via Popup or similiar
} else {
console.log(idToken)
// Get content of token
}
});
}
}
/// END Functions for Teams
// initialized on page load!
function prepareForm() {
getTeamsContext();
document.InputForm.password.focus()
}
<script/>
Those are my questions:
What causes this error?
How do I authenticate the token on manipulation and is it Teams or Azure? (Does adal.js any functions for this?)
How do I login if the silent authentication fails and popups are blocked? Is there a website for authentication provided by Teams that returns a token?
Are there any working examples of the silent authentication that are not from the official Microsoft website? (I don't understand them.)

How can I check or verify that a user is signed in with AWS Cognito Javascript?

I am creating a React web app where the user sign in/up and other authentication related processes are being handled by AWS Cognito and the accompanying Javascript SDK.
My app has some 'public' routes/pages that everybody, signed in or not, can view, such as /documentation/ and /sign-in/. There also exist various private routes which you can only see when you are logged in, such as /my-documents/.
At the moment, I have a working sign in page, where a user is signed in with code very similar to use case #4 (Cognito Docs).
My question now is: as soon as a user goes to /my-documents/, how do I check whether the user is signed in and actually has the rights to see this page?
I am not using AWS Amplify for the authentication in my app. I only use the NPM package 'amazon-cognito-identity-js'.
This is the code I currently use to check if the session is valid, in other words if the user is successfully signed in. This however, seems like a cumbersome way to check such a simple status.
const isAuthenticated = () => {
const cognitoUser = userPool.getCurrentUser();
let isSessionValid = false;
if (cognitoUser) {
cognitoUser.getSession((err: Error, result: CognitoUserSession) => {
if (!err) {
isSessionValid = result.isValid();
}
});
}
return isSessionValid;
};
isSessionValid is returned before the callback in getSession is executed.

Add Google authentication to Firebase Real Time Database

I'm using the Firebase Real Time Database and I need to add user authentication to it. Users can only login with Google as a provider.
Current database mode:
{
"rules": {
".read": true,
".write": true
}
}
New mode should be like this:
// These rules grant access to a node matching the authenticated
// user's ID from the Firebase auth token
{
"rules": {
"users": {
"$uid": {
".read": "$uid === auth.uid",
".write": "$uid === auth.uid"
}
}
}
}
What should I use to authenticate in my case? userID, Google providerID or a token like described here?
This is the function without authentication to store data:
createMeetup ({commit, getters}, payload) {
console.log('index.js -> createMeetup')
const meetup = {
title: payload.title,
}
let imageUrl
let key
firebase.database().ref('meetups').push(meetup)
.then((data) => {
key = data.key
return key
})
.then(() => {
commit('createMeetup', {
...meetup,
imageUrl: imageUrl,
id: key
})
})
.catch((error) => {
console.log(error)
})
},
For your use case it seems like you need to sort out a few steps. I'm guessing your application can already connect/use Firebase, but these are essentially it:
Step 1 - Connecting
Connect to Firebase using your API key/config as per usual, should look something like the following.
firebase.initializeApp(config)
See also: https://firebase.google.com/docs/web/setup
You probably already have this somewhere. This does not change, but if you would apply the rules as described your users would not be able to use Firebase after just connecting.
Step 2 - Authenticating
This is basically telling Firebase who is connected. This must be done with a token/method Firebase can verify. Using a Google ID is the most common method.
With an existing Google ID / user login
// Initialize a generate OAuth provider with a `google.com` providerId.
var provider = new firebase.auth.OAuthProvider('google.com');
var credential = provider.credential(googleUser.getAuthResponse().id_token);
firebase.auth().signInWithCredential(credential)
See also: https://firebase.google.com/docs/reference/js/firebase.auth.OAuthProvider#credential
Or make Firebase SDK do the login flow
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
// ...
})
See also: https://firebase.google.com/docs/auth/web/google-signin
This last option is preferred / suggested by the documentation you referenced.
If, as you described, users can already login with Google to your app for other functionalities then you should already have a login flow somewhere. Depending on your situation it might be advisable to let the Firebase SDK / library take over this process for simplicity in your application.
Step 3 - Using the database
Lastly, after authenticating users and applying the rules you suggested you will need to also make sure the paths you write to are within those accessible by the current user. You can put this in a simple function to make it easier.
const getUserRef = (ref) => {
const user = firebase.auth().currentUser;
return firebase.database().ref(`/users/${user.uid}/${ref}/`);
}
You should of course not be retrieving the current user every time you want to get a database reference, but I think this clearly illustrates the steps that need to be taken.
You can allow users to login/auth using multiple methods. Then you can merge them together to a single account as described here:
https://firebase.google.com/docs/auth/web/account-linking
So really it boils down to two options:
Allow users to login with multiple methods such as Facebook, Google, Github, basic username/password, etc.
Or allow only a single login method such as Google only.
Whichever options you pick will help you decide which ID to use.
The auth rules in your question are only stating that the users can read/write their own (presumably) user data.
I assume that you are rather looking for a solution to authorize the user to create meetup data and you should crerate rules similar to this:
These rules allow any user that is logged in to create meetups
{
"rules": {
"meetups": {
"$meetupId": {
".read": "auth.uid != null",
".write": "auth.uid != null"
}
}
}
}
Your code-snippet that pushes new meetup data to the database will automatically try and succeed or fail depending on whether the user was logged in or not. You don't need to specifically tell Firebase in which way the user was logged in. Firebase SDK will take care of the authentication for you.
But if you do want to provide different mechanisms depending on which login type that the user is authenticated with, you can check it in the rules. For example if you want to make sure that the user is not just "anonymously" logged in.
See the documentation: https://firebase.google.com/docs/database/security/user-security#section-variable
the documentation has you covered there: Authenticate Using Google Sign-In with JavaScript.
You can let your users authenticate with Firebase using their Google Accounts by integrating Google Sign-In into your app. You can integrate Google Sign-In either by using the Firebase SDK to carry out the sign-in flow, or by carrying out the Google Sign-In flow manually and passing the resulting ID token to Firebase.
Before you begin:
Add Firebase to your JavaScript project.
Enable Google Sign-In in the Firebase console:
In the Firebase console, open the Auth section.
On the Sign in method tab, enable the Google sign-in method and click Save.
Handle the sign-in flow with the Firebase SDK
If you are building a web app, the easiest way to authenticate your users with
Firebase using their Google Accounts is to handle the sign-in flow with the
Firebase JavaScript SDK. (If you want to authenticate a user in Node.js or
other non-browser environment, you must handle the sign-in flow manually.)
To handle the sign-in flow with the Firebase JavaScript SDK, follow these steps:
Create an instance of the Google provider object:
var provider = new firebase.auth.GoogleAuthProvider();
Optional: Specify additional OAuth 2.0 scopes that you want to request from the authentication provider. To add a scope, call addScope().
For example:
provider.addScope('https://www.googleapis.com/auth/contacts.readonly');
See the authentication provider documentation.
Optional: To localize the provider's OAuth flow to the user's preferred language without explicitly passing the relevant custom OAuth parameters, update the language code on the Auth instance before starting the OAuth flow.
For example:
firebase.auth().languageCode = 'pt';
// To apply the default browser preference instead of explicitly setting it.
// firebase.auth().useDeviceLanguage();
Optional: Specify additional custom OAuth provider parameters that you want to send with the OAuth request. To add a custom parameter, call setCustomParameters on the initialized provider with an object containing the key as specified by the OAuth provider documentation and the corresponding value.
For example:
provider.setCustomParameters({
'login_hint': 'user#example.com'
});
Reserved required OAuth parameters are not allowed and will be ignored. See the authentication provider reference for more details.
Authenticate with Firebase using the Google provider object. You can prompt your users to sign in with their Google Accounts either by opening a pop-up window or by redirecting to the sign-in page. The redirect method is preferred on mobile devices.
To sign in with a pop-up window, call signInWithPopup:
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
// ...
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
Also notice that you can retrieve the Google provider's OAuth token which can be used to fetch additional data using the Google APIs.
This is also where you can catch and handle errors. For a list of error codes have a look at the Auth Reference Docs.
To sign in by redirecting to the sign-in page, call signInWithRedirect:
firebase.auth().signInWithRedirect(provider);
Then, you can also retrieve the Google provider's OAuth token by calling getRedirectResult() when your page loads:
firebase.auth().getRedirectResult().then(function(result) {
if (result.credential) {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
// ...
}
// The signed-in user info.
var user = result.user;
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});

Administrator Views for a Firebase Web Application: How To

My Firebase web app requires administrator access, i.e., the UI should show a few things only for admins (an 'administrator' section). I came up with the below as a means to authorize the UI to display the admin section for valid admins only. My question is, good or bad? Is this a sound means of authorizing? ...so many ways to do this. This particular way requires me to configure admins in the security rules (vs in a node/tree in a db/firestore)
My idea is that if the .get() fails due to unauthorized access, I tell my app logic the user is not an admin, if the .get() succeeds my logic shows the 'admin' sections. Of course, the 'sections' are just HTML skeletons/empty elements populated by the database so even if the end user hacks the JS/logic, no real data will be there - only the empty 'admin section' framework.
function isAdmin(){
return new Promise(function(resolve, reject){
var docRef = firebase.firestore().collection("authorize").doc("admin");
docRef.get().then(function(result) {
if (result) {
resolve (true);
}
}).catch(function(error) {
resolve (false);
});
});
}
The firestore rule specifies the 'admins' by UID.
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth.uid == "9mB3UxxxxxxxxxxxxxxxxxxCk1";
}
}
}
You're storing the role of each user in the database, and then looking it up in the client to update its UI. This used to be the idiomatic way for a long time on realtime database, and it still works on Firestore.
The only thing I'd change is to have the rules also read from /authorize/admin, instead of hard-coding the UID in them. That way you only have the UID in one place, instead of having it in both the rules and the document.
But you may also want to consider an alternative: set a custom claim on your admin user, that you can then read in both the server-side security rules (to enforce authorized access) and the front-end (to optimize the UI).
To set a custom claim you use the Firebase Admin SDK. You can do this on a custom server, in Cloud Functions, but in your scenario it may be simpler to just run it from your development machine.
Detailed How To: Firebase has what's called Custom Claims for this functionality as detailed in their Control Access with Custom Claims and Security Rules. Basically, you stand up a separate node server, install the Firebase AdminSDK:
npm install firebase-admin --save
Generate/Download a Private Key from the Service Accounts tab in the Firebase Console and put that on your node server. Then simply create a bare bones node app to assign Custom Claims against each UID (user) that you wish. Something like below worked for me:
var admin = require('firebase-admin');
var serviceAccount = require("./the-key-you-generated-and-downloaded.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://xxxxxxxxxxxxxxxxxxxx.firebaseio.com"
});
admin.auth().setCustomUserClaims("whatever-uid-you-want-to-assign-claim-to", {admin: true}).then(() => {
console.log("Custom Claim Added to UID. You can stop this app now.");
});
That's it. You can now verify if the custom claim is applied by logging out of your app (if you were previously logged in) and logging back in after you update your web app's .onAuthStateChanged method:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
firebase.auth().currentUser.getIdToken()
.then((idToken) => {
// Parse the ID token.
const payload = JSON.parse(window.atob(idToken.split('.')[1]));
// Confirm the user is an Admin.
if (!!payload['admin']) {
//showAdminUI();
console.log("we ARE an admin");
}
else {
console.log("we ARE NOT an admin");
}
})
.catch((error) => {
console.log(error);
});
}
else {
//USER IS NOT SIGNED IN
}
});

Categories