500 Internal error in oidc authentication redirect callback using passportJS, only happens deployed in cloud, works when hosted on localhost - oauth

Thank you in advance I have searched in forum, did not find good answers.
I have a simple authentication service implemented with passportJS and openid-client, everything works fine when the service is hosted locally (http://localhost:4021), but I get an http 500 internal server error on the "redirect callback" when deployed on AWS cloud which has an https URL.
My debug shows it never returns to the Strategy callback when the 500 error is thrown. Strategy is imported from "openid-client".
I have doubled checked the redirect URL config, it looks good.
Here is my service code for authentication:
app.get('/login', (req, res) => {
.......
const client = new oidcIssuer.Client({
client_id: myID,
client_secret: mySecret,
redirect_uris: [`${MY_ENDPOINT}/auth/callback`],
response_types: ['code']
});
client[custom.clock_tolerance] = 5;
passport.use('oidc',
new Strategy({ client, passReqToCallback: true }, async (req, tokenSet, userinfo, done) => {
accUserInfo = userinfo;
return done(null, tokenSet);
})
);
const options = {
scope: openid
};
passport.authenticate('oidc', options)(req, res,
(err) => {
next();
});
});
Here is my handler for the callback:
app.get('/auth/callback', (req, res, next) => {
console.log('in the callback');
});
Everything works fine when the service is hosted locally (http://localhost:4021), but I get an http 500 internal server error on the "redirect callback" when deployed on the cloud which has an https URL.

Related

Axios post request network error on android

So i'm posting a formdata object with axios to a node.js server. On iOS everything works perfectly, the data get posted and the image uploaded. But on android i'm getting this error
[AxiosError: Network Error]
here's my axios call
const handleSubmit = async (listing, { resetForm }) => {
const data = new FormData();
listing.images.forEach((image, index) =>
data.append("images", {
name: `product${Math.floor(Math.random() * 1000)}.`,
uri: image,
})
);
const res = await axios
.post("http://192.168.43.8:5000/products/addProduct", data, {
headers: {
"Content-Type": "multipart/form-data",
},
//tried adding this but didn't work out
transformRequest: (data) => data,
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
// handle error
});
}
}
Please note that on iOS it works without a problem.
here's a screenshot of the error when i used the react native debugger
if you use android emulator you need to change your ip to 10.0.2.2
change this:
http://192.168.43.8:5000/products/addProduct
to this:
http://10.0.2.2:5000/products/addProduct
By default http calls are blocked from android 9 version onwards, you either need to make your api calls HTTPS or you need to explicitly allow connection to this IP in your manifest file. Please refer this SO thread. How to allow all Network connection types HTTP and HTTPS in Android (9) Pie?
For me i am getting axios error for my emulator and did not getting any error for ios simulator. The problem with my emulator is that it is not able to connect to Internet.
So I added google DNS server 8.8.8.8 (you can add any DNS server) for my mac and it worked.

Cross origin error when using cloud functions in back4app

Getting CORS error when calling cloud function in back4app.
Error:
Access to XMLHttpRequest at
'https://parseapi.back4app.com/functions/hello' from origin
'http://localhost:8100' has been blocked by CORS policy: No 'Access-
Control- Allow-Origin' header is present on the requested resource.
In client code cloud function implemented in home page
home.page.ts:
Parse.Cloud.run('hello').then(function (ratings) {
console.log("updated");
}).catch((error) => {
console.log(error);
console.log("fail");
});
Cloud function:
In back4app added main.js file with cloud code implementation
main.js:
Parse.Cloud.define('hello', function(req, res) {
Parse.Cloud.useMasterKey();
return 'Hi';
});
It can be related to the Parse Server version.
Can you please take a look to check what is the Parse Server version that you are using? Please, find this info following this guide.
If it is 2.X, you must deploy a function with the structure below:
main.js:
Parse.Cloud.define('hello', function(req, res) {
response.success('Hello')
});
The code Parse.Cloud.useMasterKey(); is deprecated. Read more here.
If it is the 3.X, you can deploy something like:
Parse.Cloud.define('hello', (req) => {
return 'Hello';
});
Check if you have initialized the correct keys on your frontend side.
If it still doesn't work, please contact the Back4App team in the live chat =D

How to create SendBird user with SendBird Platform API and Request node library

We are building a react-native chat app. We are implementing a back end authentication solution on google Firebase. The creation of a new user in Firebase Auth triggers a cloud function which should create a new SendBird user with an access token. The access token will be stored in Cloud Firestore, ready for retrieval the next time the user logs in.
We are having trouble implementing the POST request that creates the new user via the platform API. We are using the Request library for node.js. We are able to reach the API endpoint, but the following object is returned: { message: 'SendBird API Endpoint.', error: true }. There is no indication of what the error may be.
This happens when sending the request to the base url. When we send the request to /users or /v3/users, we receive a 403 error.
Any indication as to what may be causing this problem would be greatly appreciated.
Below is the cloud function index.js code
const functions = require('firebase-functions');
const admin = require("firebase-admin");
const request = require('request');
admin.initializeApp();
exports.handleNewUser = functions.auth.user().onCreate((user) => {
var newUserRequestBody = {
"user_id": user.email,
"nickname": user.email,
"profile_url": "",
"issue_access_token": true,
}
request.post({
headers: {
'Content-Type': 'application/json, charset=utf8',
'Api-Token': // API Token
},
url: 'https://api-{application_id}.sendbird.com',
form: newUserRequestBody
}, function(error, response, body){
if (!error && response.statusCode === 200) {
const info = JSON.parse(body);
console.log("request successful");
console.log(response.statusCode);
console.log(info);
}
else{
console.log("request unsuccessful");
console.log(response.statusCode);
console.log(error);
}
});
return null;
});
Did you try with full path of end point to url: (including /v3/users)?
Or you may need to use "baseUrl" like below?
https://github.com/request/request#requestoptions-callback
Also, you need to make sure that you correctly used {application_id} value and {API Token} value.
You can double check this from your dashboard of SendBird.
http://dashboard.sendbird.com > Log in with your ID > select your APP.
There is a section named "App credentials" in "Overview" menu.
You can double check your API-request URL and API-Token value from there.

Using Oauth 2.0 with Next js

I want to use Google OAuth 2.0 with my React/Next.js app. I've set up my OAuth Client IDs on the Google Developer console, and set up a route in my server.js node file. When I try to GET request https://localhost:3000/auth/google I get the Next js 404 Not Found page. It's obviously looking for a page called auth in my Next js pages directory. Tried using the next/Router, wrapping my button in an anchor element, fetch API GET requesting https://localhost:3000/auth/google, all failed.
I've managed to successfully implement passport user authentication, salting, hashing and sessions but it's just the Oauth that's giving me trouble.
If it were a standard node application https://localhost:3000/auth/google would redirect to the interface where users could login with their google credentials.
I've tried search the nextjs examples github for implementations of oauth but there doesn't seem to be any. Anyone know how I can use OAuth 2.0 with Next JS?
Route
server.get("/auth/google", (req, res) =>{
passport.authenticate("google", { scope: ['profile']});
})
Button that's supposed to take me to the google login/register page
<button className="btn btn-block btn-social btn-google" style={{'color': '#fff'}} onClick={() => Router.push("/auth/google")}>
<FontAwesomeIcon icon={faGoogle} className="google-social-button" /> Sign Up with Google
</button>
You can simply try this,
const app = next({ dev });
const server = express()
server.get('/auth/google/callback*',
passport.authenticate('google'),
(req, res) => {
res.redirect('/dashboard');
});
server.get('/auth/google*', (req, res) => {
return app.render(req, res, req.path, req.query)
});
server.get('/api/logout', (req, res) => {
req.logout();
res.send(req.user);
})
server.get('/api/current_user', (req, res) => {
res.send(req.user);
});
server.get('*', (req, res) => {
return handle(req, res)
});
Just make sure the google reqs are above the server.get('*') route as it catches all requests.
More help: https://github.com/zeit/next.js/blob/canary/examples/custom-server-express/server.js
Not sure if you're still looking for an answer here, but if are, you can do something like the following under the latest Next.js version (9+), https://nextjs.org/blog/next-9#api-routes
//--- PART 1: DEFINE YOUR GOOGLE OAUTH STRATEGY ALA PASSPORT
// This would be in its own passport.js file (the filename doesn't matter), the key thing being that you define your Google Strategy
import passport from 'passport'
import {
Strategy as GoogleStrategy,
} from 'passport-google-oauth20'
passport.use(new GoogleStrategy({
...getGoogleKeySecret(), // a utility for grabbing your secret keys
callbackURL: `/api/authorize/google/callback`,
passReqToCallback: true, // http://www.passportjs.org/docs/authorize/
}, async function(req, accessToken, refreshToken, profile, done) {
// Do any user lookup/mapping you need here
return done(null, profile)
}))
//--- PART 2: DEFINE THE END-POINT
// This would be in your pages/api/auth/google.js file
import nextConnect from 'next-connect'
import middleware from '../any/custom/middleware/stuff/you/may/have'
const handler = nextConnect()
handler.use(middleware)
handler.get(passport.authenticate("google", {
scope: ['profile', 'email', 'openid'], // tailer the scope to fit your needs
}))
export default handler
To try it out, direct a user to /api/auth/google via your UI or hit the URL directly, and you should be taken through the Google OAuth 2.0 flow.
Hope this helps - good luck!

react native app auth plugin network error

I tried to create a react native app with OAuth login in my rails app.
I have this react native setup
const config = {
issuer: 'http://app.domain.tld',
clientId: '85bb84b9cb0528b1f64b7c77586507b3ca5e69b11abe36ae1e54e88a6150c21e',
clientSecret: '0d3c0713437e0028a121a0c2294cc9a72f4eb5609416935a2860e20f176c7855',
redirectUrl: 'com.domain://com.domain',
responseType: 'code',
scopes: [],
dangerouslyAllowInsecureHttpRequests: __DEV__,
// clientAuthMethod: 'post',
serviceConfiguration: {
authorizationEndpoint: 'http://app.domain.tld/oauth/authorize',
tokenEndpoint: 'http://app.domain.tld/oauth/token',
// revocationEndpoint: 'http://app.domain.tld/oauth/revoke'
},
additionalParameters: {
approval_prompt: 'force'
}
}
// use the client to make the auth request and receive the authState
try {
const result = await authorize(config)
// result includes accessToken, accessTokenExpirationDate and refreshToken
console.log('result', result)
} catch (error) {
console.log('error', error.message)
}
the oaut app looks like this:
When I press the button to login in my app, I get a browser window where I can login in my rails app and got redirected to the authorize page for the oauth app. After I authorize my app, I got redirected to the app with the message "Network error". With that message I can't find out whats wrong, maybe anyone can help me.
In the server logs I can see this:
Redirected to com.domain://com.domain?code=54f3b4c03ea3724522f9a7983e2ea1b9037336076cd52cb875f9654d5d79784a&state=8xmiicVcPKN980ZDZUwBnw
in the debugger-ui i get this error log:
error Error: Network error
at createErrorFromErrorData (ReactNativeART.js:10)
at ActivityIndicator.js:72
at MessageQueue.__invokeCallback (ReactNativeART.js:472)
at blob:http://localhost:8081/1fccf34b-97b0-4c42-81fa-f0e1391a3ad3:2358
at MessageQueue.__guard (ReactNativeART.js:373)
at MessageQueue.invokeCallbackAndReturnFlushedQueue (blob:http://localhost:8081/1fccf34b-97b0-4c42-81fa-f0e1391a3ad3:2357)
at debuggerWorker.js:80
so i think there is something wrong. The app didn't make any further request to the server to obtain the access_token. Whats wrong?
Use this in config:
dangerouslyAllowInsecureHttpRequests: true,

Resources