AWS SDK cognito Custom Challenge (Missing required parameter ANSWER) - amazon-cognito

Am using AWS SDK nodejs, currently doin CUSTOM CHALLENGE with phone number as USERNAME.
Able to receive SMS using "InitiateAuth "
Request:
const input: Cognito.InitiateAuthCommandInput = {
ClientId: process.env['Cognito_clientId'],
AuthFlow: Cognito.AuthFlowType.CUSTOM_AUTH,
AuthParameters: {
USERNAME: phoneNo
},
};
Response:
{
"result": {
"$metadata": {
"httpStatusCode": 200,
"requestId": "3b657d1e-0bc9-4688-8d8d-262a15423f61",
"attempts": 1,
"totalRetryDelay": 0
},
"ChallengeName": "CUSTOM_CHALLENGE",
"ChallengeParameters": {
"USERNAME": "+60xxxxxxx"
},
"Session": "AYABeET-_lEjNtSjk92wys9dJeIAHQABAAdTZXJ2aWNlABBDb2duaXRvVXNlclBvb2xzAAEAB2F3cy1rbXMAUGFybjphd3M6a21zOmFwLXNvdXRoZWFzdC0xOjAzMTU3NzI0MDA0ODprZXkvYmEwNzA1YzktMTI0Mi00ODg1LWJhMmYtNDhiMWNjYTNiNDNmALgBAgEAeMtRirmB1qptVeI5EWSyPpLL6RXz-VVK9JVsLMBfSNNmAap9HYRwVToFU4Xvt9DcvfoAAAB-MHwGCSqGSIb3DQEHBqBvMG0CAQAwaAYJKoZIhvcNAQcBMB4GCWCGSAFlAwQBLjARBAxjxbxqrEx0kP7n7g4CARCAO6LG6jTd1lWHaNb69h-_ot85fKE-RWSBUn0NbAHZY06v7HNclPRTei8NIncvXzIUGMzibmSl9OE05hotAgAAAAAMAAAQAAAAAAAAAAAAAAAAAGX9wUB-dnBMvCx0hTb_xfD_____AAAAAQAAAAAAAAAAAAAAAQAAAPNDFLwOwHcyee5zQVZ4C5oGGEw0k730misyMIysJEg4ZpKkKTdbKMHg8FJgqhlw14UmTk-y-AJqUAr3yu7XhiPhM38Aa3DKxKGPtIDxt0aKZZyPga2RVIVhA0oW_UNlbU9TRzPoG7qph1HhCCTY6XTrT8nNFtGVyuUoPLh4lrUT-3BMQwVphz6oyxrUD8kUvD-tGjyKYhStn6Tljv3ooymkHNv3CGSY93W4KNzQPM410ld24nhJXE1D_gJNhtFQblCepVKf_54BrTNQqcbTSAwZ6o28yIEHEyUYlbK1OYN70vwB1k17uPeOxfVf3YW3xisLItnIn4eAX5UwYjiJSABl-kO2"
}
}
Based on documentation, should be calling "RespondToAuthChallenge" API next. But keep getting "Missing required parameter ANSWER"
https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_RespondToAuthChallenge.html
Request:
const input: Cognito.RespondToAuthChallengeCommandInput = {
ClientId: process.env['Cognito_clientId'],
ChallengeName: ChallengeNameType.CUSTOM_CHALLENGE,
ChallengeResponses: {
USERNAME: phoneNo
},
Session: body.session
};
Response:
InvalidParameterException: Missing required parameter ANSWER
Any idea what is wrong?
Thanks

Add ANSWER to your ChallengeResponses object that you send in to RespondToAuthChallenge:
const input: Cognito.RespondToAuthChallengeCommandInput = {
ClientId: process.env['Cognito_clientId'],
ChallengeName: ChallengeNameType.CUSTOM_CHALLENGE,
ChallengeResponses: {
USERNAME: phoneNo,
ANSWER: /*add sms code or similar here..*/
},
Session: body.session
};

Related

React Blitz.js 3rd party auth failing with passport-azure-ad

I'm attempting to swap the default auth scheme in Blitz.js with a passport-azure-ad scheme, using the OIDCStrategy. I'm getting an error that I'm not sure about and would appreciate any help! I've created a new file under src/pages/auth/openid.tsx and into inserted the following code:
import { passportAuth } from "#blitzjs/auth"
import { api } from "src/blitz-server"
import { OIDCStrategy } from "passport-azure-ad"
const users: Array<{ oid: string }> = []
var findByOid = function (oid, fn) {
console.log("failing")
for (var i = 0, len = users.length; i < len; i++) {
const user = users[i]
console.log("we are using user: ", user)
if (user && user.oid === oid) {
return fn(null, user)
}
}
return fn(null, null)
}
export default api(
passportAuth({
successRedirectUrl: "/",
errorRedirectUrl: "/",
strategies: [
{
strategy: new OIDCStrategy(
{
identityMetadata:
"https://login.microsoftonline.com/<tenant-nam>.onmicrosoft.com/v2.0/.well-known/openid-configuration",
clientID: <client-id>,
responseType: "code id_token",
responseMode: "form_post",
redirectUrl: "http://localhost:3000/auth/openid/callback",
allowHttpForRedirectUrl: true,
clientSecret: "<client-secret>",
validateIssuer: false,
passReqToCallback: true,
scope: ["profile", "offline_access", "https://graph.microsoft.com/mail.read"],
loggingLevel: "info",
nonceMaxAmount: 5,
useCookieInsteadOfSession: false,
cookieEncryptionKeys: [
{ key: "12345678901234567890123456789012", iv: "123456789012" },
{ key: "abcdefghijklmnopqrstuvwxyzabcdef", iv: "abcdefghijkl" },
],
},
function (iss, sub, profile, accessToken, refreshToken, done) {
if (!profile.oid) {
return done(new Error("No oid found"), null)
}
// asynchronous verification, for effect...
process.nextTick(function () {
findByOid(profile.oid, function (err, user) {
if (err) {
return done(err)
}
if (!user) {
// "Auto-registration"
users.push(profile)
return done(null, profile)
}
return done(null, user)
})
})
}
),
},
],
})
)
I believe the configuration is good because I can run the example from passport-azure-ad from the github examples. The only change I make is that I set redirectUrl: "http://localhost:3000/auth/openid/callback", instead of redirectUrl: ".../return", per the blitz.js third party auth documentation. The tenantname, client_id, client_secret are redacted but I do set them to the correct values. I have also verified that the app registration is correctly set with the correct redirect uri.
I run blitz dev and when I go to the http://localhost:3000/auth/openid route I get the following error.
Here is the console output that is produced:
As you can see there is a Module not found: Can't resolve './src/build', this error only occurs if I go to the auth/openid page but the app is able to load.

How to resolve Cloud Function Error:401 Unauthorized

I have coded an Apps Script that creates an event in the Calendar.
Apps Script is stand alone, and event in also created in my personal Gmail account.
This Script is linked to GCP project linked to same account as Script.
Oauth consent screen is created in the GCP account and also credentials for Oauth2.0 client ID.
Now I created a cloud function to call this appsScript but it is giving an Error:401
following is code for the cloud function
let message = req.query.message || req.body.message || 'Hello World!';
const axios = require('axios');
const {google} = require('googleapis');
//Authorization
const { GoogleAuth } = require('google-auth-library');
const auth1 = new GoogleAuth({
keyFile: 'credentials.json',
scopes: ['https://www.googleapis.com/auth/drive','https://www.googleapis.com/auth/drive.metadata'
, 'https://www.googleapis.com/auth/calendar','https://www.googleapis.com/auth/calendar.events' ],
});
const drive = google.drive({version: 'v3', auth: auth1 });
const calendar = google.calendar({version : "v3"});
//calling formSchedule function with all the variables
async function formSchedule(eventDate,claimId, garageId, claimDet,startTime,cEmailG){
//Schedule Meeting Json Data
var evDurtion=30;
var startDateTime = startTime;
var endDateTime=new Date(startDateTime.getTime()+(evDurtion*60000));
// console.log(endDateTime)
var subject="Claim ID : "+claimId+' - Call';
var attendees=[{
"email": garageId,
},
];
var eventData={
"summary":subject,
'start': {
'dateTime': startDateTime,
'timeZone': 'Asia/Kolkata'
},
'end': {
'dateTime': endDateTime,
'timeZone': 'Asia/Kolkata'
},
"attendees":attendees,
"conferenceData": {
"createRequest": {
"conferenceSolutionKey": {
"type": "hangoutsMeet"
},
"status": {
"statusCode": "success"
},
"requestId": "test1235"
}
},
"description":claimDet,
"defaultReminders": [
{
"method": "popup",
"minutes": "5"
}
]
}
console.log("after all variables initialization")
// Schedule Meeting
axios({
method: "post",
url : //API Executable deployed Apps Script link,
data: {
'eventdata' : eventData,
'serviceId' : cEmailG
},
headers: {
'Content-Type': 'text/plain;charset=utf-8',
},
}).then(function (response) {
try{
console.log('Event Added Successfully.')
}
catch (error){
console.log('------error-----',error)
}
})
}
res.status(200).send(message);
};```

swagger-ui-express persistAuthorization not working

I have a very simple sample code using swagger-ui-express:
const express = require("express");
app = express();
app.listen(3000);
const swaggerUi = require('swagger-ui-express');
var options = {
swaggerOptions: {
persistAuthorization: true
}
};
app.use('/doc',
swaggerUi.serve, swaggerUi.setup(
{
"swagger": "2.0",
"info": {
"title": "Simple API overview",
"version": "v2"
},
securityDefinitions: {
BearerAuth: {
type: 'apiKey',
in: 'header',
name: 'Authorization'
},
},
}
,
options
)
);
I am not able to mak persistAuthorization work, after entering anything in the authorization field, when refreshing the web page the authorization is deleted.
The code follows the documentation in https://www.npmjs.com/package/swagger-ui-express
And the persistAuthorization option is documented in https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/

Expo - React Native: How to read User data from Google Fit API

thanks in advance for any assistance that can be provided. My goal is to use OAuth2 to get users’ step data from the Google Fit API. I am able to authenticate using Expo's expo-app-auth package, and receive an accessToken, but, when I try to read from the Fit API, I get an error that the authentication credential is missing.
Relevant Code:
let config = {
issuer: 'https://accounts.google.com',
scopes: ['openid', 'profile', 'https://www.googleapis.com/auth/fitness.activity.read'],
/* This is the CLIENT_ID generated from a Firebase project */
clientId: 'xxx.apps.googleusercontent.com',
};
let authState = await AppAuth.authAsync(config); // this returns an idToken, accessToken, list of scopes configured, including the fitness.activity.read
const url = 'https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate';
const today = new Date().getTime();
const past = today - (5 * 24 * 60 * 60 * 100);
const body = {
"aggregateBy": [{
"dataTypeName": "com.google.step_count.delta",
"dataSourceId": "derived:com.google.step_count.delta:com.google.android.gms:estimated_steps"
}],
"bucketByTime": { "durationMillis": 86400000 },
"startTimeMillis": today,
"endTimeMillis": past
}
const header = {
'Content-Type': 'application/json',
'Authorization': `BEARER ${authState.accessToken}`
}
const req = await fetch(url, {
method: 'POST',
headers: header,
body: JSON.stringify(body)
});
const resp = await req.json();
/*
Object {
"error": Object {
"code": 401,
"errors": Array [
Object {
"domain": "global",
"location": "Authorization",
"locationType": "header",
"message": "Login Required.",
"reason": "required",
},
],
"message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED",
},
}
*/
I am able to produce this issue using a built apk on a real device. For the standalone build, I am using an OAuth2 clientId from Google Console as clientId in the config, and the Fitness API is enabled.
Does anyone know what I might be doing incorrectly?

Backand: Sign user in immediately after registering?

Having trouble doing this - is it even possible?
Sign-up Email Verification is off, and I'm doing this in the config:
BackandProvider.setAppName( 'test' );
BackandProvider.runSigninAfterSignup( true );
// ... tokens, etc.
Getting this back in the response after hitting the /1/user/signup endpoint:
data : {
currentStatus : 1,
listOfPossibleStatus : [...],
message : "The user is ready to sign in",
token : "...",
username : "tester#test.com"
}
Do I need to make another API call? Can't find where and with which params.
Yes, you must make another API call to get token after sign up. If you use the Backand SDK by default it makes the second call.
$scope.signup = function (form) {
return Backand.signup(form.firstName, form.lastName,
form.username, form.password,
form.password,
{company: form.company})
.then(function (response) {
$scope.getUserDetails();
return response;
});
};
If you lool at the SDK code, this is what happens there:
self.signup = function (firstName, lastName, email, password, confirmPassword, parameters) {
return http({
method: 'POST',
url: config.apiUrl + urls.signup,
headers: {
'SignUpToken': config.signUpToken
},
data: {
firstName: firstName,
lastName: lastName,
email: email,
password: password,
confirmPassword: confirmPassword,
parameters: parameters
}
}).then(function (response) {
$rootScope.$broadcast(EVENTS.SIGNUP);
if (config.runSigninAfterSignup
&& response.data.currentStatus === 1) {
return self.signin(email, password);
}
return response;
})
};