I am working on a nodejs express application. I used Passport's JSON web token for authentication. I have successfully created a JSON web token and it's working fine in Postman and also verifies when token passes into authorization. But I stuck on front-end side.
app.get('/profile',passport.authenticate('jwt',{session:false}),function(req,res){
// res.json({user:user.req});
// console.log(req.query.token);
res.json('bingo u cant see this without token')
});
How do I send the token in the headers like I did in Postman to this (/profile) route, i.e how to implement token on front end side so that it first checks token?
It depends on the kind what you are using to make your request at the frontend
if you are using ajax, do something like this
$.ajax({
type: 'POST',
url: url,
headers: {
"authToken":"your token" //you could save it in localstorage when recieved
}
//OR
//beforeSend: function(xhr) {
// xhr.setRequestHeader("My-First-Header", "first value");
// xhr.setRequestHeader("My-Second-Header", "second value");
//}
})
and if it's axios try doing it like this
post(url, {
headers: { authToken: token }
})
Related
I am trying to add a Sign in with Twitter option on my Chrome extension with this code:
// Send request to our backend, which calls
// https://api.twitter.com/oauth/request_token to get the OAuth token
const response = await postData({
url: '/auth/twitter/reverse',
headers: { 'Content-Type': 'application/json' }
});
const authUrl = new URL('https://api.twitter.com/oauth/authenticate');
authUrl.searchParams.set('oauth_token', response.data.oauth_token);
authUrl.searchParams.set('force_login', 'false');
chrome.identity.launchWebAuthFlow({ url: authUrl.href, interactive: true }, (responseUrl) => {
// responseUrl is undefined
});
The OAuth dialog appears, and I can sign into Twitter successfully. When the window closes, it shows this error message in the console: Unchecked runtime.lastError: Authorization page could not be loaded.
My OAuth flow works fine on a website. I realize the Chrome Identity API is made for OAuth 2, so I'm not sure if there's a way to make Twitter OAuth 1.0a work with it.
How can I further debug and fix this issue?
I fixed it! I was using a different callback URL than the https://<app_id>.chromiumapp.org/ one.
Here's the updated code for making a request to my backend:
// Send request to our backend, which calls
// https://api.twitter.com/oauth/request_token to get the OAuth token
const response = await postData({
url: '/auth/twitter/reverse',
data: {
callbackUrl: chrome.identity.getRedirectURL()
},
headers: { 'Content-Type': 'application/json' }
});
...
My backend had the callback URL hardcoded, so I made it use the one passed in the request body.
Next, on the Twitter Developer Portal, I added my https://<app_id>.chromiumapp.org/ URL to the Callback URI / Redirect URL section.
Remember, of course, to replace app_id with the name of your Chrome Extension app ID.
I currently have a web application that uses React frontend + Express sessions backend for authentication and authorization. I'm wondering if I can use the same or similar workflow for authenticating mobile users. This is how I authenticate users in my web application:
req.session.user = { id: user.rows[0].id }; // Set session cookie with user's ID
res.status(200).json({status: "success", message: "Login successful"});
It's very simple. If the passed login credentials are correct - I create a session with the user's ID that comes from the database and return a success to the front end.
Can I do something similar when using React Native as front end? I'm new to mobile development, but does the mobile client even have a cookie storage similar to a web browser? Very thankful for any input :)
Yes you can use cookies for authentication, I recommend to use fetch function to do http request. You need to pass access-control-allow-credentials header to share the cookies between server and client.
Example:
var params = {
method: "POST",
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'access-control-allow-credentials': 'true'
}
}
params.body = JSON.stringify(body)
const response = await fetch(url, params)
const json = await response.json()
Call the exact same function from react native as it is from react and persist data using this library react-native-async-storage.
I'm using the github oauth to authenticate user,so during the setup I used redirect route as my backend url (eg :http://localhost:4000/home).
After getting the token to that route,I perform a http request to url
(https://github.com/login/oauth/access_token?client_id=${clientID}&client_secret=${clientSecret}&code=${requestToken})
In order to get the access token of user.
My question is after I receive this access token,I pass this to front-end just as a parameter in url(which is visible to user).
Eg: res.redirect(http://localhost:3000/home/${accessToken})
So I just want to make it invisible to user by passing it through response header. How can I do this????
// Declare the redirect route
app.get('/home', (req, res) => {
// The req.query object has the query params that
// were sent to this route. We want the `code` param
const requestToken = req.query.code
axios({
// make a POST request
method: 'post',
// To the Github authentication API, with the client ID, client secret and request token
url: `https://github.com/login/oauth/access_token?client_id=${clientID}&client_secret=${clientSecret}&code=${requestToken}`,
// Set the content type header, so that we get the response in JSON
headers: {
accept: 'application/json'
}
}).then((response) => {
// Once we get the response, extract the access token from the response body
const accessToken = response.data.access_token
// redirect the user to the welcome page, along with the access token
res.redirect(`http://localhost:3000/home/${accessToken}`)
})
})
I keep getting an unauthenticated error back when submitting my request to the Google My Business API in my Node.js app. The response:
{
"error": {
"code": 401,
"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"
}
}
For what it's worth, I'm using the request-promise client to make the request. My function is below. I just received the access token, so I'm fairly certain that it's good, and I can see it through the err.options.Authorization log. I know the location ID doesn't exist yet, but I don't think that's what the error is telling me.
const request = require('request-promise');
...
function checkLocation (loc) {
return request({
method: 'GET',
uri: `https://mybusiness.googleapis.com/v4/accounts/${ACCOUNT_ID}/locations/${loc._id}`,
Authorization: `OAuth ${ACCESS_TOKEN}`
})
.then(function (response) {
console.log(response);
})
.catch(function (err) {
console.error(err.error, err.options.Authorization);
});
}
Is my request formatted incorrectly or am I not sending all I need to be?
Update: I left out possibly crucial information that this is through the one time authorization process for server-side apps like outlined here: https://developers.google.com/identity/protocols/OAuth2. My trouble is wrapped up in the sentence on that page, "After an application obtains an access token, it sends the token to a Google API in an HTTP authorization header."
Turned out my header wasn't formatted correctly. The Authorization key should be in a headers object:
{
method: 'GET',
uri: `https://mybusiness.googleapis.com/v4/accounts/${ACCOUNT_ID}/locations/${loc._id}`,
headers: {
Authorization: `OAuth ${ACCESS_TOKEN}`
}
}
Working with a vendor with minimal API and new to OAuth2. Using npm packages oauth and request.
Creating a node module which would post data from a database to the server's API.
I've got the authorization token, but now I'm unsure how to send that with the data post request. The vendor server is responding with a simple Cannot POST /accounts/import.
So - how do I send the OAuth2 token back with the post data to the server?
var request = require('request'),
clcreds = require('../../creds/creds.js');
var OAuth = require('oauth');
var OAuth2 = OAuth.OAuth2;
var oauth2 = new OAuth2(clcreds.clientId, clcreds.clientSecret, 'https://URL.com/', null, 'token', null);
oauth2.getOAuthAccessToken('', {
'grant_type': 'client_credentials'
}, function(e, access_token, refresh_token, results) {
console.log(e, access_token, refresh_token, results);
request.post('https://URL.com/accounts/import', {
"accounts": [{
...
}]
}, function(e, r, body) {
//returns Cannot POST /accounts/import
})
})
Most resource servers support RFC 6750, 2.1. Authorization Request Header Field. If your server supports it, you can pass an access token to the server by adding Authorization header like below.
Authorization: Bearer YOUR-ACCESS-TOKEN
If your server does not support any means defined in RFC 6750, you have to ask the implementor of the server about how to pass an access token to the server.