Access Youtube Channel ID once signed in though Firebase GoogleAuthProvider - firebase-authentication

I've setup a basic Firebase authentication app which uses Google. I've passed the following scopes:
https://www.googleapis.com/auth/youtube.force-ssl
When logging in, it states that it is gaining permission to manage my Youtube Account, but the response I get back has nothing relevant to Youtube in it, such as a channelId.
Even when doing a simple $http.get request against the logged in accounts Youtube subscriptions I get the following response:
The request uses the <code>mine</code> parameter but is not properly authorized.
So would I need to login through Google, then authenticate again once signed in to access my Youtube account?
Sample login:
var provider = new firebase.auth.GoogleAuthProvider();
provider.addScope("https://www.googleapis.com/auth/youtube.force-ssl");
$scope.login = function () {
Auth.$signInWithPopup(provider).then(function (result) {
console.log(result);
console.log("Signed in as:", result.user.uid);
}).catch(function (error) {
console.error("Authentication failed:", error);
});
}

Apologies in the delay.
Here is how I solved this problem. When logging in using Firebase with Google as a provider, I get the access_token given by Google and query YouTubes API to get the correct channel.
An example of my login function is below:
this.loginMainGoogle = function (event) {
gapi.auth2.getAuthInstance().signIn().then(function _firebaseSignIn(googleUser) {
var unsubscribe = $rootScope.authObj.$onAuthStateChanged(function (firebaseUser) {
unsubscribe();
// Check if we are already signed-in Firebase with the correct user.
if (!_isUserEqual(googleUser, firebaseUser)) {
// Build Firebase credential with the Google ID token.
console.log(googleUser.getAuthResponse());
var credential = firebase.auth.GoogleAuthProvider.credential(
googleUser.getAuthResponse().id_token);
// Sign in with credential from the Google user.
return $rootScope.authObj.$signInWithCredential(credential)
.then(function (result) {
var ytToken = googleUser.getAuthResponse().access_token;
localStorage.setItem('gToken', ytToken);
$rootScope.tokenerino = ytToken;
$http.get("https://www.googleapis.com/youtube/v3/channels?part=id&mine=true&access_token=" + ytToken)
.then(function(response) {
$rootScope.myChan = response.data.items[0].id;
localStorage.setItem('myChannelId', $rootScope.myChan);
updateYTChannel(result.uid, response.data.items[0].id);
});
$rootScope.currentLoginStatus = true;
$rootScope.notification("You Have Signed In");
//Don't redirect them if they login via a YouTube playlist
if ($location.path().indexOf('playlists') !== 1) {
$state.go('mymusic');
}
}, function errorCallback(error) {
console.log(error);
});
}
})
});
}
I store the Channel for the user in Firebase, but you can put it in localStorage if you want. The only problem is that the access_token only lasts for 1 hour. Hopefully this helps anyone and if a better solution has been found - feel free to share!

Related

OAuth 2Client: Invalid token signature

I wanted to handle my user auth by google.
async verify(token) {
try {
const ticket = await client.verifyIdToken({
idToken:token,
audience: '245409008225-isc00em81fk0vs423pm4jmgc2hcma5jj.apps.googleusercontent.com',
});
const payload = ticket.getPayload();
return payload
} catch (error) {
console.log(error)
}
this code works fine, only for first time to create user in DB. And i save this token to localstorage and retrieve it every time to validate that user is authentificated. Here is my code:
async isAuth(token) {
if (!token) {
false
}
const userData = tokenService.verify(token);
const tokenFromDb = await tokenService.findToken(token);
if (!userData || !tokenFromDb) {
throw ApiError.UnAuthorizedError();
}
const user = await User.findOne({where: {email: userData.email}});
await tokenService.saveToken(token);
return true;
}
I did google, and i supposed to define jwk key for google auth api? But I can't find real solution. So, hope you guys can help me. I never used before google auth. For now I have this solution by making request to this api https://www.googleapis.com/oauth2/v1/tokeninfo?id_token=token and getting from there my user email

How to debug invalid_grant during authorization code exchange?

My application is using OAuth to access the Youtube Data API. My OAuth callback is written in node and uses the OAuth2Client class from the "googleapis" npm package to exchange the authorization code for the access and refresh tokens.
Everything was working fine up to last week until suddenly I started getting the "invalid_grant" response during the authorization code exchange. I have tried everything to resolve this and am running out of ideas. My callback executes as a cloud function so I don't think that it would be out of sync with NTP.
My OAuth consent screen is in "Testing" mode and my email address is included in the test users. The odd thing is that even though the authorization code exchange fails, my Google account's "Third-party apps with account access" section lists my application as if the handshake succeeded.
Here is my code for generating the auth URL and exchanging the authorization code. The invalid_grant occurs during the call to "oauth2.getToken"
async startFlow(scopes: string[], state: string): Promise<AuthFlow> {
const codes = await oauth2.generateCodeVerifierAsync();
const href = oauth2.generateAuthUrl({
scope: scopes,
state,
access_type: 'offline',
include_granted_scopes: true,
prompt: 'consent',
code_challenge_method: CodeChallengeMethod.S256,
code_challenge: codes.codeChallenge
});
return { href, code_verifier: codes.codeVerifier };
}
async finishFlow(code: string, verifier: string): Promise<Tokens> {
const tokens = await oauth2.getToken({ code, codeVerifier: verifier })
return {
refresh_token: tokens.tokens.refresh_token!,
access_token: tokens.tokens.access_token!,
expires_in: tokens.tokens.expiry_date!,
token_type: 'Bearer',
scopes: tokens.tokens.scope!.split(' ')
};
}
"oauth2" is an instance of OAuth2Client from "google-auth-library". I initialize it here:
export const oauth2 = new google.auth.OAuth2({
clientId: YT_CLIENT_ID,
clientSecret: YT_CLIENT_SECRET,
redirectUri: `${APP_URI}/oauth`
});
Looking at the logs, the only out of the ordinary thing I notice is that the application/x-www-form-urlencoded body looks slightly different than the example https://developers.google.com/identity/protocols/oauth2/web-server#exchange-authorization-code
The POST request to "https://oauth2.googleapis.com/token" ends up looking like this:
code=4%2F0AX4XfWiKHVnsavUH7en0TywjPJVRyJ9aGN-JR8CAAcAG7dT-THxyWQNcxd769nzaHLUb8Q&client_id=XXXXXXXXXX-XXXXXXXXXXXXXXX.apps.googleusercontent.com&client_secret=XXXXXX-XXXXXXXXXXXXXXX-XX_XXX&redirect_uri=https%3A%2F%2Fapp.example.com%2Foauth&grant_type=authorization_code&code_verifier=KjOBmr4D9ISLPSE4claEBWr3UN-bKdPHZa8BBcQvcmajfr9RhWrgt7G429PLEpsP7oGzFGnBICu3HgWaHPsLhMkGBuQ2GmHHiB4OpY2F0rJ06wkpCjV2cCTDdpfRY~Ej
Notice that the "/" characters are not percent-encoded in the official example, but they are in my requests. Could this actually be the issue? I don't see how the official google auth library would have an issue this large.
If you check the documentation on expiration of refresh tokens you will see
A Google Cloud Platform project with an OAuth consent screen configured for an external user type and a publishing status of "Testing" is issued a refresh token expiring in 7 days.
Set your project to production mode and your refresh tokens will last longer then a week.
library
IMO if your refresh token expires your library should be requesting access again. However the library was created before the change that a refresh token gets revoked. This isnt a true refresh token expired error message and the library isn't detecting that.
A post over on the issue forum for your library may encourage them to patch it so that it is more obvious of an error message.
At any rate you need to delete the stored tokens for that user which will request authorization again.
update If its not that.
ensure that your computer / server has the correct time
revoke the users access directly via their google account. Under third party apps with access ensure that your app isnt listed if it is remove it.
Make sure that you are using the correct client type from google developer console.
Google node.js sample
var fs = require('fs');
var readline = require('readline');
var {google} = require('googleapis');
var OAuth2 = google.auth.OAuth2;
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/youtube-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/youtube.readonly'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'youtube-nodejs-quickstart.json';
// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
// Authorize a client with the loaded credentials, then call the YouTube API.
authorize(JSON.parse(content), getChannel);
});
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
*
* #param {Object} credentials The authorization client credentials.
* #param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, callback) {
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var oauth2Client = new OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function(err, token) {
if (err) {
getNewToken(oauth2Client, callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
}
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
*
* #param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
* #param {getEventsCallback} callback The callback to call with the authorized
* client.
*/
function getNewToken(oauth2Client, callback) {
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Authorize this app by visiting this url: ', authUrl);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the code from that page here: ', function(code) {
rl.close();
oauth2Client.getToken(code, function(err, token) {
if (err) {
console.log('Error while trying to retrieve access token', err);
return;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});
}
/**
* Store token to disk be used in later program executions.
*
* #param {Object} token The token to store to disk.
*/
function storeToken(token) {
try {
fs.mkdirSync(TOKEN_DIR);
} catch (err) {
if (err.code != 'EEXIST') {
throw err;
}
}
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
if (err) throw err;
console.log('Token stored to ' + TOKEN_PATH);
});
}
/**
* Lists the names and IDs of up to 10 files.
*
* #param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function getChannel(auth) {
var service = google.youtube('v3');
service.channels.list({
auth: auth,
part: 'snippet,contentDetails,statistics',
forUsername: 'GoogleDevelopers'
}, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
var channels = response.data.items;
if (channels.length == 0) {
console.log('No channel found.');
} else {
console.log('This channel\'s ID is %s. Its title is \'%s\', and ' +
'it has %s views.',
channels[0].id,
channels[0].snippet.title,
channels[0].statistics.viewCount);
}
});
}
I've discovered my problem. Another part of my code was throwing an error while the authorization request was being sent (some weird async code). This caused the request to bail halfway through and send only a partial body. This resulted in the invalid_grant appearing in my logs which misled me to believe this was the root cause of my problem.
I fixed the other piece of my code and now the authorization request succeeds without issue.

auth0 checkSession({}) returns login_required when logged in through social provider, but not when logging in via username/password

I have an Angular app that uses Auth0 for authentication, and I'm trying to use checkSession({}, …) to persist a user's session if the token hasn't expired yet.
When I log in with my username/pw that I set up for the site, this works fine when I reload the browser/navigate directly to a resource. However, when I log in using a social provider (such as Google), the checkSession({}, …) call on a page reload returns an error and forces the user to log in again.
Some of the relevant code (mostly from the auth0 tutorial(s)):
export class AuthService {
// Create Auth0 web auth instance
private _auth0 = new auth0.WebAuth({
clientID: AUTH_CONFIG.CLIENT_ID,
domain: AUTH_CONFIG.CLIENT_DOMAIN,
responseType: 'token',
redirectUri: AUTH_CONFIG.REDIRECT,
audience: AUTH_CONFIG.AUDIENCE,
scope: AUTH_CONFIG.SCOPE
});
accessToken: string;
userProfile: any;
expiresAt: number;
// Create a stream of logged in status to communicate throughout app
loggedIn: boolean;
loggedIn$ = new BehaviorSubject<boolean>(this.loggedIn);
loggingIn: boolean;
isAdmin: boolean;
// Subscribe to token expiration stream
refreshSub: Subscription;
constructor(private router: Router) {
// If app auth token is not expired, request new token
if (JSON.parse(localStorage.getItem('expires_at')) > Date.now()) {
this.renewToken();
}
}
...
handleAuth() {
// When Auth0 hash parsed, get profile
this._auth0.parseHash((err, authResult) => {
if (authResult && authResult.accessToken) {
window.location.hash = '';
this._getProfile(authResult);
} else if (err) {
this._clearRedirect();
this.router.navigate(['/']);
console.error(`Error authenticating: ${err.error}`);
}
this.router.navigate(['/']);
});
}
private _getProfile(authResult) {
this.loggingIn = true;
// Use access token to retrieve user's profile and set session
this._auth0.client.userInfo(authResult.accessToken, (err, profile) => {
if (profile) {
this._setSession(authResult, profile);
this._redirect();
} else if (err) {
console.warn(`Error retrieving profile: ${err.error}`);
}
});
}
private _setSession(authResult, profile?) {
this.expiresAt = (authResult.expiresIn * 1000) + Date.now();
// Store expiration in local storage to access in constructor
localStorage.setItem('expires_at', JSON.stringify(this.expiresAt));
this.accessToken = authResult.accessToken;
this.userProfile = profile;
if (profile) {
this.isAdmin = this._checkAdmin(profile);
}
...
}
...
get tokenValid(): boolean {
// Check if current time is past access token's expiration
return Date.now() < JSON.parse(localStorage.getItem('expires_at'));
}
renewToken() {
// Check for valid Auth0 session
this._auth0.checkSession({}, (err, authResult) => {
if (authResult && authResult.accessToken) {
this._getProfile(authResult);
} else {
this._clearExpiration();
}
});
}
}
(This is from a service that is called in many places within the app, including some route guards and within some components that rely on profile information. If more of the app code would be useful, I can provide it.)
Also note: AUTH_CONFIG.SCOPE = 'openid profile email'
So, the issue appears to not have been related to my app at all. When using Social Providers, Auth0 has an explicit note in one of their tutorials that really helped me out:
The issue with social providers is that they were incorrectly configured in my Auth0 dashboard, and needed to use provider-specific app keys.
Important Note: If you are using Auth0 social connections in your app,
please make sure that you have set the connections up to use your own
client app keys. If you're using Auth0 dev keys, token renewal will
always return login_required. Each social connection's details has a
link with explicit instructions on how to acquire your own key for the
particular IdP.
Comment was found on this page: https://auth0.com/blog/real-world-angular-series-part-7/

Signing Out of Google Sign In

I have a site that users can use their Google accounts to authetnicate with. The sign out page is not working, though. I automatically get signed in when I revisit the login page. Can anyone tell me why my page is not signing Google users out?
https://bluezero.xyz/logout.asp
The solution was to nest the call to getAuthInstance() within init()'s Promise, a la:
function signOut() {
gapi.load('auth2', function() {
gapi.auth2.init().then(function(){ /// THIS WAS THE SOLUTION HERE
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function(){
console.log("User is logged out");
});
});
});
}
Google's recommended method did not work:
// FROM GOOGLE (https://developers.google.com/identity/sign-in/web/sign-in#sign_out_a_user)
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () { // THIS FAILED BECAUSE getAuthInstance() HADN'T COMPLETED
console.log('User signed out.');
});
}

React Native Firebase for Facebook Provider Authentication not working

I've followed this post on Medium to try to implement firebase authentication: https://blog.invertase.io/getting-started-with-firebase-authentication-on-react-native-a1ed3d2d6d91
I firstly implemented the Social Authentication with Facebook and it worked fine, but after that, when I successfully finished the Google Authentication part, the Facebook part was stuck at the line
return firebase.auth().signInWithCredential(credential);
Because It didn't return the user Promise after that so the Firebase onAuthStateChanged cannot log the user in
The function that handle facebook authentication:
onLoginOrRegisterFacebook = () => {
LoginManager.logInWithReadPermissions(["public_profile", "email"])
.then(result => {
if (result.isCancelled) {
return Promise.reject(new Error("The user cancelled the request"));
}
// Retrieve the access token
return AccessToken.getCurrentAccessToken();
})
.then(data => {
// Create a new Firebase credential with the token
const credential = firebase.auth.FacebookAuthProvider.credential(
data.accessToken
);
// Login with the credential
return firebase.auth().signInWithCredential(credential);
})
.then(user => {
})
.catch(error => {
const { code, message } = error;
});
};
The Facebook Sign In Method in Google Firebase Authentication Console is also enabled with enough information of my FB app, I also paste the OAuth redirect URI to my Facebook app configuration, and the Dashboard of Facebook Developer also successfully shows the installed app user.