swagger-ui-express persistAuthorization not working - express

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/

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.

AWS SDK cognito Custom Challenge (Missing required parameter ANSWER)

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
};

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);
};```

Strapi / Nuxt - Can't find custom route

I've used this to setup auth in strapi and nuxt:
Auth with Strapi and Nuxt
I'm currently trying to retrieve the items specific to a authenticated user (already checked out this strapi - restrict user to fetch only data related to him). To do this I created a custom route in Strapi (/api/routine/config/routes.json):
{
"method": "GET",
"path": "/routines/me",
"handler": "Routine.me",
"config": {
"policies": []
}
}
and a custom controller (/api/controllers/Routine.js):
module.exports = {
me: async (ctx) => {
const user = ctx.state.user;
if (!user) {
return ctx.badRequest(null, [{ messages: [{ id: 'No authorization header was found' }] }]);
}
const data = await strapi.services.routine.find({user:user.id});
if(!data){
return ctx.notFound();
}
ctx.send(data);
},
};
I already gave permission through Strapi admin for authenticated users to access 'me'. When I hit the endpoint from Nuxt:
const routines = await axios.get(http://localhost:1337/routines/me)
I get this error:
GET http://localhost:1337/routines/me 404 (Not Found)
Why is the custom route not found? Am I using the wrong endpoint?
Maybe you have already solved it, but it seems like you forget to send the authentication header with the request.
const routines = await axios.get(
'http://localhost:1337/routines/me', {
headers: {
Authorization:
this.$auth.getToken('local'),
},
}
It was a fault in my Strapi routes config. Answer was provided through the amazingly helpful Strapi forums:
403 forbidden when calling custom controller from Nuxt
Here is the problem:
{
"method": "GET",
"path": "/routines/:id",
"handler": "routine.findOne",
"config": {
"policies": []
}
},
{
"method": "GET",
"path": "/routines/me",
"handler": "routine.me",
"config": {
"policies": []
}
So basically you are hitting the first route right now and it assumes that
me is actually an :id. Koa is making the verifications with regex so in this case it takes the first matched route. Move the route with /me above that one with /:id

How to execute Google Cloud Functions from Firebase Hosting?

I'm trying to create an Android project which can send notifications from one android device to another. For that purpose, I created a node.js file, it's working fine on the local server. But when I hosted it on Google Cloud Platform, it shows Page Not Found. It is not able to call Google Function from hosting. It is looking for or executing index.html but it should execute index.js, which is in functions directory which was created while initializing the project with Firebase.
I took the reference from this video: https://youtu.be/pnysHgQvOiM?list=PLk7v1Z2rk4hjM2NPKqtWQ_ndCuoqUj5Hh
index.js file
const functions = require('firebase-functions');
var {google} = require('googleapis')
var MESSAGING_SCOPE ="https://www.googleapis.com/auth/firebase.messaging"
var SCOPES = [MESSAGING_SCOPE]
var express = require('express')
var app = express();
var bodyParser = require('body-parser');
var router = express.Router();
var request = require('request');
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
router.post('/send',function(req,res){
getAccessToken().then(function(access_token){
var title = req.body.title;
var body = req.body.body;
var token = req.body.token;
request.post({
headers:{
Authorization: 'Bearer '+ access_token
}, url:
"https://fcm.googleapis.com/v1/projects/my_project_name/messages:send",
body: JSON.stringify(
{
"message":{
"token" : token,
"notification" : {
"body" : body,
"title" : title
}
}
}
)
},function(error,reponse,body){
res.end(body);
console.log(body);
});
});
});
app.use('/api',router);
function getAccessToken()
{
return new Promise(function(resolve,reject){
var key= require("./service-account.json");
var jwtClient = new google.auth.JWT(
key.client_email,
null,
key.private_key,
SCOPES,
null
);
jwtClient.authorize(function(error,tokens){
if(error)
{
reject(error)
}
resolve(tokens.access_token)
// console.log(tokens.access_token)
});
jwtClient.authorize(function(error,tokens){
if(error)
{
reject(error)
}
resolve(tokens.access_token)
console.log(tokens.access_token)
});
});
}
exports.api = functions.https.onRequest(app);
firebase.json
{
"hosting":
{
"public": "public",
"rewrites": [
{
"source": "/api/send",
"functions": "api"
}
],
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
]
}
}
This code is working fine with using http://localhost:8085/api/send but it is not working as https://my_project_name.firebaseapp.com/api/send