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 ?
Related
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
I can download user events but not user managed pages. Why? What is the difference?
Using react-facebook-login to get user access token
import FacebookLogin from "react-facebook-login";
Adding Facebook login to the screen, it has the pages_show_list permission:
<FacebookLogin
appId={fbAppId}
autoLoad={true}
fields="name,email,picture"
scope="public_profile,pages_show_list"
onClick={this.componentClicked}
callback={this.responseFacebook}
And here is the handler:
responseFacebook = response => {
this.setState({
accessToken: response.accessToken,
isLoggedIn: true,
userID: response.userID,
name: response.name,
email: response.email,
picture: response.picture.data.url
});
axios.get('https://graph.facebook.com/v5.0/me/accounts&access_token='+response.accessToken)
.then(response => {
console.log("aaa " + response);
console.log("bbb ");
})
};
Second breakpoint will not be reached.
But get a lot of strange error:
Facebook API Explorer returns the data
Code is here: https://gitlab.com/j4nos/ticket-portal/blob/master/src/App.js
But get a lot oof strange error:
Focus.
The main part of importance here is that it shows that you are getting a 400 Bad Request response from the API, with that URL you tried to request there.
https://graph.facebook.com/v5.0/me/accounts&access_token=...
How does the query string portion of a URL start again ...?
Question mark, not ampersand.
I'm working on a react native ios app using facebook authentication and firebase.
I created my facebook app, copied the secret keys to my firebase facebook auth mode, but when i'm trying to sign in with facebook credential using firebase I'm getting this error : The supplied auth credential is malformed or has expired.
I had a look at this issue : FB login - Firebase.Auth() Error: The supplied auth credential is malformed or has expired which is the quite similar to mine, but the answer didn't help me because my keys are the same in my facebook app configuration than in my firebase facebook auth mode.
Here is the code i'm using when the facebook auth button is pressed :
facebookLogin = () => {
LoginManager.logInWithPermissions(['public_profile', 'email'])
.then(
(result) => {
if (result.isCancelled) {
Alert.alert('Whoops!', 'You cancelled the sign in.');
} else {
AccessToken.getCurrentAccessToken()
.then((data) => {
const credential = firebase.auth.FacebookAuthProvider.credential(data.accessToken);
console.log(credential);
firebase.auth().signInWithCredential(credential)
.then(() => this.props.navigation.replace('Home'))
.catch((error) => {
console.log(error.message);
this.setState({ errorMessage: error.message })
});
});
}
},
(error) => {
Alert.alert('Sign in error', error);
},
);
};
I hope you guys can help me, maybe I mistook when I configured my facebook app.
Thank you in advance.
turns out Facebook Graph API is not supported by firebase yet check this out
the reason why Graph API is not supported
Trying to get Meteor Facebook login to work. It functions fully in that it uses Facebook API and requests the correct permissions from the users account and then logs in successfully.
The problem is it doesn't save the permission requested information even though its been approved and only the basic name and ID are available in Meteor.user().services.facebook. Is this code not working because it's not saving the users details on login? I can't find a resource that details how to save or extract the other data.
Simply trying to console log the data to see that it's been extracted out of the Facebook user account on log in.
Within Meteor.isClient code:
Template.login.events({
'click #facebook-login': function(event) {
Meteor.loginWithFacebook({ requestPermissions: ['email', 'public_profile', 'user_friends', 'user_likes']}, function(err){
if (err) {
throw new Meteor.Error("Facebook login failed");
}
console.log(Meteor.user().services.facebook.name);
console.log(Meteor.user().services.facebook.id);
console.log(Meteor.user().services.facebook.email);
console.log(Meteor.user().services.facebook.gender);
});
},
'click #logout': function(event) {
Meteor.logout(function(err){
if (err) {
throw new Meteor.Error("Logout failed");
}
});
}
The config code:
ServiceConfiguration.configurations.remove({
service: 'facebook'
});
ServiceConfiguration.configurations.insert({
service: 'facebook',
appId: 'correctAppID',
secret: 'CorrectSecret'
});
For Facebook v2.4 API after you have requested for certain permissions you can then access them by making a graph API call and requesting them with a valid auth token. The code is as follows:
if (user.hasOwnProperty('services') && user.services.hasOwnProperty('facebook') ) {
var result = Meteor.http.get('https://graph.facebook.com/v2.4/' + user.services.facebook.id + '?access_token=' + user.services.facebook.accessToken + '&fields=first_name, last_name, birthday, email, gender, location, link, friends');
console.log(result.data.first_name);
console.log(result.data.last_name);
console.log(result.data.birthday);
console.log(result.data.email);
console.log(result.data.gender);
console.log(result.data.location);
console.log(result.data.link);
console.log(result.data.friends);
}
In the example of oauth2 strategy usage in the Passport's repo, the following function is presented:
passport.use(new OAuth2Strategy({
authorizationURL: 'https://www.example.com/oauth2/authorize',
tokenURL: 'https://www.example.com/oauth2/token',
clientID: EXAMPLE_CLIENT_ID,
clientSecret: EXAMPLE_CLIENT_SECRET,
callbackURL: "http://localhost:3000/auth/example/callback"
},
function(accessToken, refreshToken, profile, done) {
User.findOrCreate({ exampleId: profile.id }, function (err, user) {
return done(err, user);
});
}
));
How does Passport obtains the profile field? is it provided with the token by the oauth endpoint? or does it come from a separate (session-related) request?
When using, for example, the Facebook's oauth API, the user info is loaded automatically with the Passport's Facebook strategy, so I'm trying to figure out how does this happen and how to implement a similar behavior in a custom oauth2 API.
The user profile is typically loaded after the access_token is successfully retrieved:
https://github.com/jaredhanson/passport-oauth2/blob/master/lib/strategy.js#L175
this._oauth2.getOAuthAccessToken(code, { grant_type: 'authorization_code', redirect_uri: callbackURL },
function(err, accessToken, refreshToken, params) {
if (err) { return self.error(self._createOAuthError('Failed to obtain access token', err)); }
self._loadUserProfile(accessToken, function(err, profile) {
if (err) { return self.error(err); }
The function to actually get the user information is often provided by the specific strategy (e.g. Facebook, Twitter, etc)
In Facebook's implementation:
https://github.com/jaredhanson/passport-facebook/blob/master/lib/strategy.js#L137