I'm currently trying to authenticate users with google oauth in a react-native app with react-native-app-auth.
This is my code
import * as AppAuth from 'react-native-app-auth';
import { AuthorizationError } from '../errors';
import { GooglePeopleApis } from '#apis';
import { Platform } from 'react-native';
const IOS_CLIENT_ID = "placeholder_client_id"
const ANDROID_CLIENT_ID = "placeholder_client_id"
const IOS_REDIRECT_URI = "placeholder_ios_redirect_url"
const ANDROID_REDIRECT_URI = "placeholder_android_redirect_url"
const config = {
issuer: 'https://accounts.google.com',
clientId: Platform.select({ios: IOS_CLIENT_ID, android: ANDROID_CLIENT_ID})!,
redirectUrl: Platform.select({ios: IOS_REDIRECT_URI, android: ANDROID_REDIRECT_URI})!,
scopes: ['https://mail.google.com/', "profile", "email"]
};
export interface AuthorizationResponse {
accessToken: string;
accessTokenExpirationDate: string;
refreshToken: string;
emailAddress: string;
}
export const authorize = async (): Promise<AuthorizationResponse> => {
try {
let result = await AppAuth.authorize(config);
const emailAddress = await GooglePeopleApis.fetchMyEmailAddress(result.accessToken)
return {
accessToken: result.accessToken,
accessTokenExpirationDate: result.accessTokenExpirationDate,
refreshToken: result.refreshToken,
emailAddress
}
} catch(err) {
const error = err as Error
throw new AuthorizationError(error.message);
}
}
On ios it works fine, on android it worked the first time but then when i came back to the project the day after it started giving me an error like the following
ReactNativeJS: [Error: Invalid ID Token]
I can't understand the problem since i'm not passing any id token in the auth request.
The browser opens as expected, i select my google account but then it returns this error.
react-native: 0.66.3
react-native-app-auth: 6.4.0
Check if the emulator date and time are correct.
I was getting the same error. I went ahead and deleted the emulated device and created a new one, then it worked. Hopefully that helps you.
How to delete emulated device
Related
I am trying to authenticate through Azure Active Directory on a react native app using react-native-app-auth package which is the also the official package for this task. I have made the app registration, successfully made it to return me the "auth code" instead of "auth token", also I was able to make the mobile app redirected to the required screen. But right after returning me the "auth code" it says
[Error: Data intent is null]
The code I am using is below
import { authorize } from "react-native-app-auth";
import pkceChallenge from 'react-native-pkce-challenge';
const config = {
clientSecret: "MY_SECRET_VALUE_FROM_AAD",
issuer: 'https://login.microsoftonline.com/MY_TENANT_VALUE_FROM_AAD',
clientId: 'MY_CLIENT_ID_AT_AAD',
redirectUrl: 'com.sham://com.sham/android/callback',
scopes: [
'openid',
'profile',
'email',
],
additionalParameters: {prompt: 'select_account'},
serviceConfiguration: {
authorizationEndpoint: 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',
tokenEndpoint: 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
},
};
try {
const result = await authorize(config);
} catch (err){
console.log(err)
}
// ALSO THROUGH
const challenge = pkceChallenge();
try {
const result = await authorize({...config, code_challenge: challenge.codeChallenge, code_challenge_method: "S256"});
} catch (err){
console.log(err)
}
I have also tried to install the demo app at https://github.com/microsoftgraph/msgraph-training-react-native but that app never gets installed maybe due to old dependencies. Please point out if someone knows what mistake I might be commiting.
I am trying to authenticate my ios and android app with microsoft office 365 using react-native-app-auth package and not sure why it is not returning the token.
Here is the config that I am using:
const config = {
issuer:
'https://login.microsoftonline.com/{tenant-id}/v2.0',
clientId: '{client-id}',
redirectUrl: 'msauth.org.xxx.xxx://auth', // I got this from Azure
scopes: ['openid', 'profile', 'email', 'offline_access'],
};
I have also tried with the below config
const config = {
clientId: AuthConfig.appId,
warmAndPrefetchChrome: true,
redirectUrl: 'msauth.org.xxx.xxx://auth',
scopes: AuthConfig.appScopes,
additionalParameters: {prompt: 'select_account'},
serviceConfiguration: {
authorizationEndpoint:
'https://login.microsoftonline.com/' +
AuthConfig.tenantId +
'/oauth2/v2.0/authorize',
tokenEndpoint:
'https://login.microsoftonline.com/' +
AuthConfig.tenantId +
'/oauth2/v2.0/token',
},
};
Here is the code:
const loginWithOffice365 = async () => {
try {
let result = await authorize(config);
console.log('result', result); // This is not showing any result and not even printing any error
} catch (error) {
console.log('error', error);
}
}
I have registered the app correctly in Azure and this is the redirect url screenshot
It goes to office 365 page and I can enter my credentials and it says are you ready to login and I click continue, once I do that, it goes back to the login page. I am not sure if my redirect URL is correct because I am trying to print the token that I should get back from Microsoft.
I am just trying to print the access token. Can you please help and tell me how can I fix this?
Your redirect url should be msauth.org.xxx.xxx://auth/
You are just missing an extra '/'
After Researching for last 24 hour i have found a very effective way to verify in app purchase but didn't get proper Information . I am looking to verify product purchase .
I tried to deploy the js file to firebase cloud function but showing i have error in exports.validatePurchases = functions.database method . Can anyone please have a look on it and fix the error ?
Here is the code :
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const {google} = require("googleapis");
const publisher = google.androidpublisher('v2');
const authClient = new google.auth.JWT({
email: '',
key: '',
scopes: ['https://www.googleapis.com/auth/androidpublisher']
});
admin.initializeApp();
exports.validatePurchases = functions.database
.ref('/purchases/{uId}/{orderId}')
.onCreate((event, context) => {
const purchase = event.val();
if (purchase.is_processed === true) {
console.log('Purchase already processed!, exiting');
return null;
}
const orderId = context.params.orderId;
const dbRoot = event.ref.root;
const package_name = purchase.package_name;
const sku = purchase.sku;
const my_token = purchase.token;
authClient.authorize((err, result) => {
if (err) {
console.log(err);
}
publisher.purchases.products.get({
auth: authClient,
packageName: package_name,
productId: sku,
token: my_token
}, (err, response) => {
if (err) {
console.log(err);
}
// Result Status must be equals to 200 so that the purchase is valid
if (response.status === 200) {
return event.ref.child('is_validated').set(true);
} else {
return event.ref.child('is_validated').set(false);
}
});
});
return null;
});
The Error i have got while deploy :
Functions deploy had errors with the following functions:
validatePurchases
To try redeploying those functions, run:
firebase deploy --only functions:validatePurchases
To continue deploying other features (such as database), run:
firebase deploy --except functions
Error: Functions did not deploy properly.
In Firebase Function Log :
Code in file index.js can't be loaded.
Did you list all required modules in the package.json dependencies?
Detailed stack trace: Error: Cannot find module 'googleapis'
at Function.Module._resolveFilename (module.js:548:15)
at Function.Module._load (module.js:475:25)
at Module.require (module.js:597:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/srv/index.js:3:18)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
First, run cmd on Function Folder of your project :
Then, In order to add it as a dependency, run the following command:
$ npm install googleapis
Now Check if any functions are live on your project. If there are functions in the firebase console remove it. Now Try Deploy.
I am building an Android app using Ionic. And using the following feathers_client.js
const feathers = require('#feathersjs/feathers');
const socketio = require('#feathersjs/socketio-client');
const auth = require('#feathersjs/authentication-client');
const io = require('socket.io-client');
const socket = io('http://mydomain.example:3030');
const feathers_client = feathers();
feathers_client
.configure(socketio(socket))
.configure(auth({ storage: window.localStorage }));
module.exports = feathers_client;
When I run the app at the browser it works fine. But when I run it at an Android device I only get "NotAuthenticated".
I am assuming this is happening because FeathersJS stores the JWT token at window.localStorage and this is not available at the Android app userspace.
Two questions:
1) Is there any way to tell FeathersJS to store this token somewhere else?
2) If not, anyone faced this situation and may provide me a solution?
By the way, this is my code for authenticating:
export class SSHSettingsPage implements OnInit {
public inputEmail: string;
public inputPassword: string;
constructor() { }
ngOnInit() {
}
public performLogin($event) {
let authObj: object = { "strategy": "local", "email": this.inputEmail, "password": this.inputPassword};
client.authenticate(authObj)
.then(res => {
console.log(res);
window.localStorage.setItem("user",JSON.stringify(res.user));
window.location.href = "/download";
})
.catch(err => {
console.log(err);
window.location.href = "/login-error";
})
}
}
As mentioned in the configuration API the storage option can be passed an instance of the React Native AsyncStorage:
import {AsyncStorage} from 'react-native';
// Available options are listed in the "Options" section
app.configure(auth({
storage: AsyncStorage
}))
I am making an app with react native. It has login with facebook option, it keeps giving me this error. "Facebook Login Error: Can't find variable: Expo"
What am I doing wrong here?
Do I have to install some dependencies on Linux
f.auth().onAuthStateChanged(function(user) {
if(user){
//logged in
console.log('Logged in', user);
}else {
//logged out
console.log('logged out');
}
});
const { type, token} = await Expo.Facebook.logInWithReadPermissionsAsync(
'APP_ID',
{ permissions: ['email', 'public_profile'] }
);
if(type === 'success'){
const credential = firebase.auth.FacebookAuthProvider.credential(token);
firebase.auth().signInWithCredential(credential).catch((error) => {
console.log('Error...',error);
})
}
Possible Unhandled Promise Rejection (id:0): ReferenceError: Can't find variable: Expo loginWithFacebook$
Assuming you have included Facebook SDK as following
import * as Facebook from 'expo-facebook';
You shouldn't be redundantly calling Expo.Facbook but instead try
const { type, token} = await Facebook.logInWithReadPermissionsAsync...
You have forgot to import Expo
import Expo from 'expo';
But you should use expo-facebook module for facebook login for more information please read document here
https://docs.expo.io/versions/latest/sdk/facebook/