Make my web app authorize with google oAuth - oauth

I am trying to login with Google oAuth. But when ever i try to login with oAuth it ask for permission. From the code i realize that there need to add the authorization . I have gone through web and found another way to make the app authorize which is complete different than what i have used here. Is there any way so that i can just modify or add a function so that i will be able to make my app authorize with google oAuth ? I am using php and javascript for my web app.
var loginFinished = function(authResult)
{
if (authResult['status']['signed_in']) {
var btnLogOut=document.getElementById("social-integration-logout");
accessToken=authResult['access_token'];
expiresIn=authResult['expires_in'];
console.log(authResult);
gapi.client.load('oauth2', 'v2', function()
{
gapi.client.oauth2.userinfo.get()
.execute(function(resp)
{
var id = resp.id;
});
});
} else {
console.log('Sign-in state: ' + authResult['error']);
}
};
var options = {
'callback': loginFinished,
'approvalprompt': 'force',
'clientid': '',
'scope': 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile',
'requestvisibleactions': 'http://schemas.google.com/CommentActivity http://schemas.google.com/ReviewActivity',
'cookiepolicy': 'single_host_origin'
};
var renderBtn = function()
{
gapi.signin.render('btn_google_login', options);
}

Could you explain what issue you are having, i.e., what is not working? I notice that your script has 'approvalprompt': 'force', which will force the authorization dialog to always display. You may want to remove it so that returning users do not have to consent again. But I am not confident that this was your question.

Related

msal.js cannot get the refresh_token even though offline_access is available and I can see it in the return call

I use msal.js to get access to the Microsoft Graph Api and I have gotten it working for the post part.
As you can see on the images I get the refresh_token in the response payload but not in the actual output when I console log it, how do I do this ?
Then thing is I need this refresh_token as the the place they auth their microsoft account is not the same place as the data is actually shown.
Let me explain
We are a infoscreen company and we need this to show the calendar of the people who authed when they have inserted it on the presentation.
so the flow is as follows:
They install the app and login with their Microsoft 365 account to give us access to this data. (this is the part that returns the refresh token and access Token).
They go to the presentation and insert the app in the area they want to show it.
on the actual monitor that could stand anywhere in the world the calendar would now show up.
But after 1 hour the session would expire so we need to generate a new access_token and for this we need the refresh_token.
At the step of loginPopup I can see there is a refreshToken
but when I use the data it is gone, I also tried to request token silently
Also I updated to the newest version of msal-browser.min.js version 2.1 that should support it.
async function signInWithMicrosoft(){
$(".notification_box", document).hide();
$("#table_main", document).show();
const msalConfig = {
auth: {
clientId: '{CLIENTID}',
redirectUri: '{REDIRECTURI}',
validateAuthority: false
},
cache: {
cacheLocation: "sessionStorage",
storeAuthStateInCookie: false,
forceRefresh: false
},
};
const loginRequest = {
scopes: [
"offline_access",
"User.Read",
"Calendars.Read",
"Calendars.Read.shared"
],
prompt: 'select_account'
}
try {
const msalClient = new msal.PublicClientApplication(msalConfig);
const msalClientLoggedIn= await msalClient.loginPopup(loginRequest).then((tokenResponse) => { console.log(tokenResponse); });
msalClientAccounts = msalClient.getAllAccounts();
var msalInsertAccount = true;
var tableMainAsText = $("#table_main", document).text();
if(typeof msalClientLoggedIn.idTokenClaims !== 'undefined'){
if(tableMainAsText.indexOf(msalClientLoggedIn.idTokenClaims.preferred_username)>-1){
msalInsertAccount = false;
}
if(msalInsertAccount){
var tableRow = "<tr>"+
"<td>"+msalClientLoggedIn.idTokenClaims.name+" ("+msalClientLoggedIn.idTokenClaims.preferred_username+") <span style='display: none;'>"+msalClientAccounts[0].username+"</span><input type=\"hidden\" name=\"app_config[exchange_online][]\" class=\"exchange_online_authed_account\" value=\""+msalClientLoggedIn.idTokenClaims.preferred_username+","+msalClientLoggedIn.idTokenClaims.name+"\" /></td>"+
"<td class=\"last\">Fjern adgang</td>"+
"</tr>";
$("#table_body", document).append(tableRow);
$("#table_foot", document).hide();
}
}
}catch(error){
$(".notification_box", document).show();
}
}

Meteor acounts add info from Twitter accounts

I'm trying to figure out how I can add additional information from a user's Twitter account to the created account on a Meteor installation.
In particular I am trying to access the user's bio via Twitter Api v 1.1 and am not successful in doing so.
Therefore I am trying to extend Accounts.onCreateUser(function(options,user) {}); with the Twitter bio. How do I do that? And then access this data from a template?
Here's a perfect answer for returning data from Github, however I've had trouble porting this approach over to Twitter as the authenticating service: Meteor login with external service: how to get profile information?
You could do it on this way:
Accounts.onCreateUser(function (options, user){
user.profile = options.profile || {};
//Twitter returns some useful info as the username and the picture
if(user.services.twitter){
user.profile.picture= user.services.twitter.profile_image_url_https;
user.profile.username= user.services.twitter.screenName;
}
return user;
});
For getting the data from the Twitter API I´m using the node package oauth:
OAuth = Npm.require('oauth');
oauth = new OAuth.OAuth(
'https://api.twitter.com/oauth/request_token',
'https://api.twitter.com/oauth/access_token',
'consumerKey',
'secretKey',
'1.0A',
null,
'HMAC-SHA1'
);
getTwitterUserData: function (id) {
var accountUser = AccountsUserCollection.findOne({_id: id});
var url = "https://api.twitter.com/1.1/users/show.json?screen_name="+accountUser.screen_name;
oauth.get(url, 'accessToken', 'accessSecret', function (err, data, response) {
if(err){
console.log(err);
}
if(data){
Fiber(function () {
AccountsUserCollection.update({_id: accountUser._id}, {$set: {dataTwitter: JSON.parse(data)}});
}).run();
}
if(response){
Log.info(response);
}
});
}

Zend Gdata Youtube and auto login

Hello guys I need help in auto login to youtube.com to upload videos "browser-based" (and later get them data to show in a site by api). So basicly I downloaded extension from here http://framework.zend.com/downloads/latest Zend Gdata. And make it work.
It works fine (demos/.../YouTubeVideoApp). But how can i do auto login to youtube without confirmation page ("grant access" \ "deny access")? Currently I use developer key to work with youtube api.
The message of confirmation is
An anonymous application is requesting access to your Google Account for the product(s) listed below.
YouTube
If you grant access, you can revoke access at any time under 'My Account'. The anonymous application will not have access to your password or any other personal information from your Google Account. Learn more
This website has not registered with Google to establish a secure connection for authorization requests. We recommend that you continue the process only if you trust the following destination:
http://somedomain/operations.php
In general I need create connection to youtube (by api) and upload there (using my own account) video without any popups and confirmation pages.
i think all you need is to get a access token and set it to a session value "$_SESSION['sessionToken']". Combination of javascript and PHP will need to do this. previously i always have to grant access or deny it while using Picasa web API but after changes that i described below, grant or access page is no longer needed.
I have not integrated youtube with zend Gdata but have integrated Picasa web Albums using it
make a login using javascript popup and get a token for a needed scope. below is a javascript code. change your scope to youtube data as in this scope for picasa is used.. click function "picasa" on your button onclick.
var OAUTHURL = 'https://accounts.google.com/o/oauth2/auth?';
var VALIDURL = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=';
var SCOPE = 'https://picasaweb.google.com/data';
var CLIENTID = YOUR_CLIENT_ID;
var REDIRECT = 'http://localhost/YOUR_REDIRECT_URL'
var LOGOUT = 'http://accounts.google.com/Logout';
var TYPE = 'token';
var _url = OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE;
var acToken;
var tokenType;
var expiresIn;
var user;
var loggedIn = false;
function picasa() {
var win = window.open(_url, "windowname1", 'width=800, height=600');
var pollTimer = window.setInterval(function() {
console.log(win);
console.log(win.document);
console.log(win.document.URL);
if (win.document.URL.indexOf(REDIRECT) != -1) {
window.clearInterval(pollTimer);
var url = win.document.URL;
acToken = gup(url, 'access_token');
tokenType = gup(url, 'token_type');
expiresIn = gup(url, 'expires_in');
win.close();
validateToken(acToken);
}
}, 500);
}
function validateToken(token) {
$.ajax({
url: VALIDURL + token,
data: null,
success: function(responseText){
//alert(responseText.toSource());
getPicasaAlbums(token);
loggedIn = true;
},
dataType: "jsonp"
});
}
function getPicasaAlbums(token) {
$.ajax({
url: site_url+"ajaxs/getAlbums/picasa/"+token,
data: null,
success: function(response) {
alert("success");
}
});
}
//credits: http://www.netlobo.com/url_query_string_javascript.html
function gup(url, name) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\#&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url );
if( results == null )
return "";
else
return results[1];
}
Here i am making a ajax call in function "getPicasaAlbums" and setting token to a $_session there and after it i am able to get a album listing using zend queries. here is a some code of php file that i am calling using ajax in function "getPicasaAlbums".
function getAlbums($imported_from = '',$token = '') {
//echo $imported_from; //picasa
//echo $token;
$_SESSION['sessionToken'] = $token;// set sessionToken
$client = getAuthSubHttpClient();
$user = "default";
$photos = new Zend_Gdata_Photos($client);
$query = new Zend_Gdata_Photos_UserQuery();
$query->setUser($user);
$userFeed = $photos->getUserFeed(null, $query);
echo "<pre>";print_r($userFeed);echo "</pre>";exit;
}
i think this will help you a little in your task. relpace above "getAlbums" function's code with your youtube zend data code to retrieve data.
good example & referene of a login popup is here
http://www.gethugames.in/blog/2012/04/authentication-and-authorization-for-google-apis-in-javascript-popup-window-tutorial.html

Injecting Facebook JS SDK into AngularJS Controllers

I'm trying to create a facebook service for Angular so I can more easily test code that needs to use the Facebook JS SDK and Graph API for stuff.
Here's what I have so far:
app.factory('facebook', function() {
return FB;
});
window.fbAsyncInit = function () {
FB.init({
appId: 'SOME_APP_ID_HERE', // App ID
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true, // parse XFBML
oauth: true
});
};
// Load the SDK Asynchronously
(function (d) {
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) { return; }
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
})(document);
Now, I know that the actual Facebook SDK part is working... but in my controller the reference is always null.
in my controller I just have something like this:
function FooCtrl($scope, facebook) {
facebook.getLoginStatus(function(response) {
if (response.status === 'connected') {
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
// do something
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
} else {
// the user isn't logged in to Facebook.
}
});
}
Angular then gripes that it can't find a facebookProvider. Any ideas on how I can accomplish this?
Enclose your factory function with array brackets like below
app.factory('facebook', [function() {
return FB;
}]);
API docs are not clear enough. Point of having array brackets is that you can specify dependencies. It will be injected on creation of your service with AUTO.$inject. But since you don't have dependencies it will skip that task :)
Anyway, if you need dependencies you can request them like this
app.factory('facebook', ["$log", function($someCrazyLoggerService){
$someCrazyLoggerService.log("I'm Auto Injected crazy Logger");
}]);
you should take a look at this Facebook module I wrote.
First use the FacebookProvider on your app config call, something as FacebookProvider.init('yourFacebookAppIdHere');, you could also configure other settings too, and then on your controllers use the Facebook service and register to events and call methods asyncrhonously ;)
https://github.com/ciul/angularjs-facebook

401 (Unauthorized) only in release mode. Debugging, everything works perfectly! Why?

I am creating an extension for Google Chrome and I'm having trouble authenticating with Twitter.
This extension is published in this link:
As you can see, I am also consuming Dropbox API (which also works with OAuth 1.0) and it works perfectly!
To work with OAuth use a library called jsOAuth available at this link.
When the user clicks on the "Twitter", a window (popup) appears to be made ​​authentic:
//Request Windows token
chrome.windows.create({url: url, type:"popup"}, function(win){
chrome.tabs.executeScript(win.tabs[0].id, { file: "/scripts/jquery-1.7.1.min.js" }, function() {
chrome.tabs.executeScript(win.tabs[0].id, { file: "/scripts/querystring-0.9.0-min.js" }, function() {
chrome.tabs.executeScript(this.args[0], { file: "/scripts/services/TwitterPage.js" });
});
});
});
url = _https://api.twitter.com/oauth/authorize?oauth_token=XXX&oauth_token_secret=YYY&oauth_callback_confirmed=true_
TwitterPage.js code
$(document).ready(function() {
$("#allow").click(function(){
var token = $.QueryString("oauth_token");
var secret = $.QueryString("oauth_token_secret");
var data = { oauth_token: token, oauth_secret: secret };
chrome.extension.sendRequest(data);
});
});
Then the authentication window is displayed
Full link: http://i.imgur.com/tikh4.png
As you can see in the above code, a request is sent to my extension.
Following is the code that captures this request:
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
chrome.windows.remove(sender.tab.windowId, fetchAccessToken);
});
fetchAccessToken function:
fetchAccessToken = function() {
oauthObj.fetchAccessToken(function(){
console.log("This code is only executed when debug step by step")
}, failureHandler);
}
Looking at the console, the error: GET https://api.twitter.com/oauth/access_token 401 (Unauthorized) is displayed
Full image: http://i.stack.imgur.com/8MgNw.png
Questions
What is wrong?
Step by step debugging, authentication is performed successfully!?! Why?
The GET /oauth/access_token is being requested twice. One succeeds and the other doesn't. It is probably getting the 401 because the request_token is only valid once. If you stop it from executing twice it should be fine.
On a side note you are including oauth_callback even while getting an access_token. This is not preferred.

Resources