authenticating using a token in react - rest

I am trying to GET some RESTful services using the api located at https://api.mmitnetwork.com
If I make a GET request it gives me a 401 error Unathorized. In order to authenticate using their api I am suppose to make a POST to https://api.mmitnetwork.com/Token with
{"grant_type":"password", "username":"yourusername","password":"yourpassword"}
in the body get a token.
How would I do this in react?

You can use axios: https://github.com/mzabriskie/axios
axios.post(' https://api.mmitnetwork.com/Token', {
grant_type: 'password',
username: 'yourusername',
password: 'yourpassword',
}).then((response) => {
console.log('success!')
}).catch((error) => {
console.log('something went wrong :(')
})

Related

How to tell auth0 im authenticated in req.rest file

So I want to make a post request to my nextJS backend and the route i am making the req to a protected route so in my Rest client file (req.rest) I need to tell auth0 im authenticated but i do not know how to do that.
req.rest
POST http://localhost:3000/api/video
Content-Type: application/json
Authorization: Bearer cookie
{
"title": "Video",
"description": "Video description"
}
api/video.js
import { withApiAuthRequired, getSession } from "#auth0/nextjs-auth0";
import Video from "../../database/models/Video";
export default withApiAuthRequired(async function handler(req, res) {
if (req.method === "POST") {
try {
const { user } = getSession(req, res);
const newVideo = new Video({
title: req.body.title,
description: req.body.description,
ownerId: user.sub,
});
await newVideo.save();
res.json(newVideo);
} catch (error) {
res.status(500).json({ error: error.message });
}
}
});
I'm not sure I understand your question. Your API should determine if the user is authenticated by validating the bearer token value you are passing through the Authorization request header, you shouldn't need to pass additional data as separate parameters to authorize the API. If you do need additional data to determine if the user is authorized to consume the API, that should be included inside of the bearer token as a claim.
So I haven't really found a solution but I do have a workaround which is to just make new page on the frontend for requests and send the requests from there.

Google Books OAuth returns 401 even though I'm passing an access_token

I'm trying to add a book to a bookshelf using the google books API by sending an axios POST request in my express server. I need to send an access token to authorize the POST request according to the docs, and I'm getting that access token from the token client model from Google Identity Services. I have the token and I have my API key, but I can't get google to authorize the request.
Here's the call from my front end:
axios.get(
'http://localhost:5000/to-read',
{
params: {
bookId: bookId,
shelfId: shelfId,
token: token
}
})
and here's the back end:
.get((req, res) => {
const headers = {
'Authorization': req.query.token,
'Content-Type': 'application/json',
}
axios.post(
`https://www.googleapis.com/books/v1/mylibrary/bookshelves/${req.query.shelfId}/addVolume?volumeId=${req.query.bookId}&key=${process.env.REACT_APP_API_KEY}`,
{},
{headers: headers}
).then((response) => {
console.log(response);
}).catch((error) => {
console.log(error.response.data)
})
When I send the request with the API key, I get this error:
error: {
code: 401,
message: 'API keys are not supported by this API. Expected OAuth2 access token or other authentication credentials that assert a principal. See https://cloud.google.com/docs/authentication',
errors: [ [Object] ],
status: 'UNAUTHENTICATED',
details: [ [Object] ]
}
and when I remove the API key (it's optional for this call according to the docs) I get this error:
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.',
errors: [ [Object] ],
status: 'UNAUTHENTICATED',
details: [ [Object] ]
}
and https://developers.google.com/identity/sign-in/web/devconsole-project leads to a 404

Error trying to get authenticated user email with googleapis and node.js

I'm implementing auth on my website using googleapis. The function plus.people.get doesn't work. I have seen it is deprecated on some forums but it's still documented at google which has me confused. The error I get is "Legacy People API has not been used in project 328985958128 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/legacypeople.googleapis.com then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry." The webpage doesn't even load. My code is
if (!req.body.token) return res.status(500).json({ type: 'error', message: 'No access token provided.' })
const OAuth2 = google.auth.OAuth2
const oauth2Client = new google.auth.OAuth2(keys.client_id, keys.client_secret)
google.options({ auth: oauth2Client });
const plus = google.plus('v1')
oauth2Client.setCredentials({
access_token: req.body.token
})
plus.people.get({
userId: 'me',
auth: oauth2Client
}, (error, response) => {
if (error)
console.log(error)
return res.status(500).json({ type: 'error',error })
const emails = (response.data || {}).emails
You are using google.plus('v1'), which has been deprecated
Instead you should use
const service = google.people({version: 'v1', auth: oauth2Client})
to create a service object.
To perform a request an additional auhtorization is not required anymore, so:
service.people.get({
userId: 'me'
}, (error, response) => {
...
})
Further information:
Creating a service account client with node.js
People API quide for node.js

Using Axios as an Alternative to request in nodejs

I am building a flutter application that requires oauth 1 authorization for one of the third party services I am using. Because flutter oauth 1 package is restricted I decided to use the oauth 1 package that npm provides. This is the code that is used to access the user generated access token from the site.
I previously used request to make a call to the api endpoint first, to access the token and secondly to use the token recieved to make another call to a different resource endpoint
How can I use axios to make the same request, emphasis on the fact that each request needs a hmac-sha1 signed signature in the header.
Thank you.
consumer: {
key: CONSUMER KEY,
secret: CONSUMER SECRET,
},
signature_method: 'HMAC-SHA1',
hash_function(base_string, key) {
return crypto
.createHmac('sha1', key)
.update(base_string)
.digest('base64')
},
})
const request_data = {
url: 'https://www.instapaper.com/api/1/oauth/access_token/',
method: 'POST',
data: { x_auth_username : USERNAME , x_auth_password : PASSWORD , x_auth_mode : 'client_auth' },
}
request(
{
url: request_data.url,
form: request_data.data,
method: request_data.method,
headers: oauth.toHeader(oauth.authorize(request_data)),
},
function(error, response, body) {
// Process your data here
console.log(error);
console.log(response);
console.log(body);
}
)
Finally found the answer for this link to the issue created on github
https://github.com/axios/axios/issues/2771

Retrieving google photos with IONIC 3 with google photos API

I am working on an IONIC application.
In this app the user will be able to get photos from his google photos account and do some design manipulations on the image he selected.
So for that I want to use the google photos API
I did not find any example on how to accomplish this in IONIC.
So I am looking for some sample code or guid on how to get this done.
=======================================================
UPDATE
I tried to do it like this:
Login to google with: cordova-plugin-googleplus
And request the https://www.googleapis.com/auth/photoslibrary
scope
Here is the code:
//Here we do a login.
this.gplus.login({
'webClientId': '***********',
'offline': true,
'scopes': 'profile email https://www.googleapis.com/auth/photoslibrary'
}).then((res) => {
//after login we try to get the google photos albums
this.http.get('https://photoslibrary.googleapis.com/v1/albums', {
responseType: ResponseContentType.Json,
params:{
accessToken: res.accessToken,
pageSize: 50,
}
}).subscribe(res=>{
console.log('<--- google images res: ', res);
},err=>{
console.log('<--- google images err: ', err);
});
});
Now I get an error 'Expected OAuth 2 access token'
Here is the full error description:
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.
==========================================================
UPDATE 2
So after some research I am trying to get the OAuth 2 access token like this:
//Here we do a login.
this.gplus.login({
'webClientId': '***********',
'offline': true,
'scopes': 'profile email https://www.googleapis.com/auth/photoslibrary'
}).then((res) => {
//after login we need to get the OAuth 2 access
//I think like this:
this.http.post('https://www.googleapis.com/oauth2/v4/token', {
code: res.serverAuthCode,
client_id: '*****************',
client_secret: '*************',
redirect_url: '***************',
grant_type: 'authorization_code'
},{
responseType: ResponseContentType.Json
}).subscribe(res=>{
//after we got the OAuth 2 access, we try to get the google photos albums
let myHeaders= new Headers();
myHeaders.append('Content-Type', 'application/json');
this.http.get('https://photoslibrary.googleapis.com/v1/albums', {
responseType: ResponseContentType.Json,
params:{
pageSize: 50,
accessToken: {'bearer': res['_body'].access_token},
},
headers: myHeaders
}).subscribe(res=>{
console.log('<--- google images res: ', res);
},err=>{
console.log('<--- google images err: ', err);
})
},err=>{
......
})
}
}), err => {
.....
});
But still getting the same error:
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.
So now the question is how do is get an OAuth 2 access token ?