Handling redirect code with OAuth2 - node.js

I am using Instagram's API which requires OAuth2 have some questions regarding best practice for setup. For more details here: https://www.instagram.com/developer/authentication/
So a user clicks on a login button and I give a redirect href.
Log In
They then receive a popup sign in, and they have the option of signing in or not. They are then redirected and '?code=zzzzzzz'is appended to the url: "http://localhost:8080?code=zzzzzzz"
Then the instructions read:
Now you need to exchange the code you have received in the previous step for an access token. In order to make this exchange, you simply have to POST this code, along with some app identification parameters, to our access_token endpoint.
But how should I do this? I'm using Express on the backend. To serve the frontend I use this line:
var static_path = path.join(__dirname, './../build');
It isn't an API route, so I can't use the normal
app.get('/?code=zzzzzzz', function(req, res) {...}).
So how can I use the code that I received in the params?

You must change your redirect_uri on isntagram to something like:
/auth/instagram/callback
https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=http://localhost:8080/auth/instagram/callback&response_type=code
Then you can get your code with req.query.code from inside the controller.
For posting the code to isntagrams API use "request" library for nodejs

Related

JSON Web Token (JWT) is too long to pass through client URL? Node.js and Express authentication

I am trying to use JWT to authenticate a user's email address. I cannot use OAuth because a user will be signing up with their work email and will need to verify using that.
I have added a field to my User model called isVerified. I have used mailgun to send an email to the user when they go to sign up that includes a link to a verification page in the form of http://{client_url}/verification/{userToken} where the userToken is a generated token using JSON web token.... the token is created using only the user's id so there is not a lot of information in the payload.
When the user clicks on this link, they are getting a 404 Not Found error. When I manually shorten the userToken in the url, then it properly connects to the correct React Component...
How do I solve this issue?
UPDATE: I just got rid of all the periods from the JWT token and it is loading like that.... so it seems to not be an issue with the length but with the periods... My react router Route path is "/verification/:userToken" ... how do I get it to not be affected by the periods?
Since this does not trigger your component to be rendered
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjIyLCJpYXQiOjE2MTEwMDY5OTUsImV4cCI6MTYxMTAwODE5NX0.D_-RI_YvE6lyHZFtkMizuHxPs3huIE87D6UKFEywYdg
and this does
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
I would suspect that it somehow worked because you got rid of the dots.
Make sure the "." in the token prevent the url from matching your "verification/token" route ? I mean react is assuming that
"verification/eyxxxx.eyzzzz"
is not a valid route.
Try calling for example "verification/test.test.test" and see if it renders your component.

In an Express.js server, how can I send an HTML (with style and js) acquired from a HTTP request, as a response?

This is an Express.js server. I'm trying to authenticate my Instagram API.
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const axios = require('axios');
const ejs = require('ejs');
var app = express();
// bodyparser middleware setup
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var instagramClientId = '123123';
app.get('/instagram', (req, res) => {
axios({
method: 'post',
url: `https://api.instagram.com/oauth/authorize/?client_id=${instagramClientId}&redirect_uri=REDIRECT-URI&response_type=code`,
}).then((response) => {
res.send(response.data);
console.log(response.data);
}).catch((e) => {
console.log(e);
});
});
// port set-up
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`app fired up on port ${port}`);
});
This is the error I got. Looks like the html file was sent just fine, but the css and js weren't executed. You can see the error messages were all about style and js not being excuted.
Is this because I need to enable some options in my res.send() code?
I'm going to answer two questions here, the first is what I think you're actually having problems with and the second is what would technically be the answer to this question.
What I think your actual problem is: A misunderstanding of OAuth2.0
Looking at your code, it looks like you're trying to get a user to authenticate with Instagram. This is great, OAuth2.0 is fantastic and a good way to authenticate at the moment, but you've got the wrong end of the stick with how to implement it. OAuth2.0 is about redirects, not proxying HTML to the user. In this case it looks like you're using axios to make a server side call to the instagram OAuth endpoint and then sending the user that HTML. What you should actually be doing is redirecting the user to the Instagram URL you've built.
A high level of the "dance" you go through is the following.
The user requests to login with instagram by pressing a button on your website.
You send the user to an instagram URL, that URL contains your applications token plus an "approved" redirect url. Once the user has logged in with Instagram, Instagram will redirect the user to your approved redirect url.
The users browser has now been redirected to a second endpoint on your server, this endpoint recieves a one-time token from Instagram. You take that token on your server side and use axios (or similar) to make a server side request to fetch some user information such as their profile. Once you have that data, you can then create a user in your the database if needed and issue a new session token to them. Along with the profile call on this, you'll also get a token given directly to you (different from the one the users browser gave you) which will allow you to make requests to the Instagram API for the privileges you requested from the user originally.
This means you have 2 endpoints on your service, the "hello, I'd like to log in with instagram, please redirect me to the instagram login page" and then "hello, instagram said I'm all good and gave me this token to prove it, you can now check with them directly" (this is the callback endpoint).
You can manage this whole process manually which is great for understanding OAuth, or you can use something like Passport.js to abstract this for you. This lets you inject your own logic in a few places and handles a lot of the back and forth dance for you. In this instance, I'd probably suggest handling it yourself to learn how it all works.
Ultimately, you are not sending the user any HTML via res.send or anything similar. Instead your first endpoint simply uses a res.redirect(instagramUrl). You also thus do not make any HTTP requests during this portion, you do that on the "callback" after they've entered their username and password with Instagram.
Technically the correct answer to this question: proxy the JS and CSS calls, but this is really bad for security!
You're sending some HTML from a 3rd party in this case. So you will need to also allow the user access to the HTML and CSS. Security wise, this is quite iffy and you should really consider not doing this as it's bad practice. All of the JS and CSS links in the page are most likely relative links, meaning they're asking you for some JS and CSS which you are not hosting. Your best bet is to find these exact paths (ie: /js/app.min.js) and to then proxy these requests. So you'll create a new endpoint on your service which will make a request to instagrams /js/app.min.js and then send that back down with res.send.
Again, please do not do this, pretending to be another service is a really bad idea. If you need something from instagram, use OAuth2.0 to authenticate the user and then make requests using their tokens and the official instagram API.

How to Get Current User in Backend with Firebase in Node.js?

I am so confused,
all the Firebase authentication tutorial online are teaching how to login in frontend,
of course you can get the token and send it to server for verification if its a post request,
but what about normal get request like a page request? I have installed firebase-admin already but i didnt find any method for getting current user........
i am using node and express
for example
app.get('/', function(req, res) {
const idToken = (where can i get the token??)
console.log(idToken);
res.render('index.ejs');
});
You still have to arrange for the auth token to be sent in the HTTP request. You can do that with a header in the request. Sample code showing exactly this case can be found in the official samples. This will work for any HTTP method, and is a lot better than trying to use a POST body.
The sample uses the Authorization header to transmit the token and verifyIdToken() to make sure it's valid.

Can I use the passport-google callback to authenticate android/ios users?

I have a node.js server which authenticates using google-passport-oauth2. My server-side code looks like that from the documentation:
app.get('/auth/google',
passport.authenticate('google', { scope:
[ 'https://www.googleapis.com/auth/plus.login',
, 'https://www.googleapis.com/auth/plus.profile.emails.read' ] }
));
app.get( '/auth/google/callback',
passport.authenticate( 'google', {
successRedirect: '/auth/google/success',
failureRedirect: '/auth/google/failure'
}));
I figure that /auth/google redirects to google's login, and when permissions are recieved, the google profile and token are sent to the callback /auth/google/callback.
Now I am making an android app which wants to authenticate with this API. I'm using the directions for integrating Google Sign-In to do the authentication on google's end. Now my android app has the profile and token and wants to verify it with my server.
I've tried doing this with passport-google-token and passport-google-id-token (not sure the difference...), but it didn't work for whatever reason. Now I'm looking at other possibilities, like a Google Client API library for node.js, but it seems bulky. Then there's the tokeninfo endpoint, which involves an extra request and more latency. Or maybe I should look at express-jwt?
And suddenly, I wonder... couldn't I just pass the token from my android app to the server at auth/google/callback? That would make things a little simpler. I think this must be a pipe dream, because I haven't found any information about doing it. But if it's possible, how should I format the token/profile data in the request so the passport.authenticate() method recognizes it? (JSON, form data, headers)
If this can't be done, I'm taking suggestions for well-documented token verification libraries for node...
I still don't know about reusing the google-passport-oauth2 route, but I did figure out how to validate Google's idToken using passport-google-id-token.
The documentation says:
The post request to this route should include a JSON object with the
key id_token set to the one the client received from Google (e.g.
after successful Google+ sign-in).
But it only works if it's sent as a query string (GET or POST works).
https://localhost:8888/auth/googletoken?id_token=xxxxxxxxxx
I have a feeling this is not the most secure method, but I'll have to deal with that later.
EDIT: It turns out, the token is useless without the client ID (in your app), so it's OK to send it by querystring.
EDIT 2: One of the google-id-token devs has reminded me that the JSON will only be received if body-parser has been installed.

Using spotify-web-api-node to generate an authentication token

I am new to using nodejs and am working on a project where I can make a custom playlist by adding one song at a time via a search. I've been able to get the code to do the searching and grabbing the proper ids done, but when trying to add to the playlist, I'm getting an error about the scope being wrong. Long story short, I was doing the wrong type of authentication.
So I read up on the spotify-web-api-node documents, but I'm getting lost between generating the authorization url and then getting the response, which is then used by another method to get the authorization token. I'm not sure if there is another method I'm not seeing that will make the request, or if I'm just supposed to do a regular request out via normal node methods.
The code I'm using is pretty much a copy-paste from the following link (https://github.com/thelinmichael/spotify-web-api-node#authorization), where the second box with the header "The below uses a hardcoded authorization code..." is where I'm lost... I need to get that code from the response, but I'm not sure how I'm to send the request to even get the response, the createAuthorizeURL method just seems to make the actual url but not send it.
I believe the confusion stems from the way the Authorization Code flow works, and the way I've written the documentation for the node wrapper. The purpose of the createAuthorizeURL method is to help you create the URL that you need to forward the user to.
From the same piece of documentation that you linked to:
In order to get permissions, you need to direct the user to our Accounts service.
Generate the URL by using the wrapper's authorization URL method.
So let's say that the user starts out by entering your site, http://www.jd.example.com. It'll have a Spotify styled button that says Login here. The button links to the URL that the createAuthorizeURL has generated. One very important part of the URL is the redirect_uri query parameter. For example, the URL that you would generate would look something like
https://accounts.spotify.com:443/authorize?client_id=5fe01282e44241328a84e7c5cc169165&
response_type=code&redirect_uri=https://www.jd.example.com/callback&
scope=playlist-modify-public
When the user clicks the button they will be taken through the authentication and authorization flow on Spotify's site (accounts.spotify.com/). However, when they've finished this flow, they will be directed by Spotify to the same redirect_uri that you gave in the createAuthorizeURL, e.g. https://www.jd.example.com/callback.
This means that your web server (e.g. Express) needs to be able to handle a request to the redirect_uri. If your web server was indeed Express, it may look like this.
/* Some express.js setup here */
/* Some spotify-web-api-node setup here */
/* Handle authorization callback from Spotify */
app.get('/callback', function(req, res) {
/* Read query parameters */
var code = req.query.code; // Read the authorization code from the query parameters
var state = req.query.state; // (Optional) Read the state from the query parameter
/* Get the access token! */
spotifyApi.authorizationCodeGrant(code)
.then(function(data) {
console.log('The token expires in ' + data['expires_in']);
console.log('The access token is ' + data['access_token']);
console.log('The refresh token is ' + data['refresh_token']);
/* Ok. We've got the access token!
Save the access token for this user somewhere so that you can use it again.
Cookie? Local storage?
*/
/* Redirecting back to the main page! :-) */
res.redirect('/');
}, function(err) {
res.status(err.code);
res.send(err.message);
}
});
});
Hope this helps!

Resources