I have ngOauth access_token now what? - android

So I am trying to add a login with facebook / twitter option to my mobile app. I have installed ngcordova oauth plugin and everything is working. User clicks login, it takes them to FB, they accept the permissions, takes them back to the app, and I have the access_token object. Perfect. Except what do I do with it now? Now that I have the token I should be able to request the specific info I need (email / name) How is this done? Do I have to install the ios & android facebook sdk and the ios & twitter sdk? Is this built into ionic? can I simply use web calls? I am very confused on how I actually get user email / whatever other info I requested in the access_token after I retrieve permission. Here is my code currently
$scope.facebookLogin = function() {
$cordovaOauth.facebook("xxxxxxxxxxxxx", ["email"]).then(function(result) {
// results
console.log("Success");
console.log(result);
}, function(error) {
// error
console.log("Failure");
console.log(error);
});
}
I am getting in the success block, but now I need to know what to do with the access_token to actually get values.

This is the solution that I found that actually works for future persons
$accessToken = result.access_token;
$http.get("https://graph.facebook.com/v2.4/me", { params: { access_token: $accessToken, format: "json" }}).then(function(result) {
//this is where the user data is stored
var user_data = result.data;
console.log(user_data);
}, function(error) {
console.log(error);
});

Related

React native app auth (android) shows two apps with same redirect scheme?

Click here to view screenshot here
I am using react native app auth with Azure active directory and in android after redirecting back to the app, two apps are shown (like in the above screenshot) , if i select the correct app the app works as expected, but if i select the other, the app crashes. How can i fix this issue and show only one app!
const config = {
issuer: 'https://login.microsoftonline.com/your-tenant-id',
clientId: 'your-client-id',
redirectUrl: 'urn:ietf:wg:oauth:2.0:oob',
scopes: [], // ignored by Azure AD
additionalParameters: {
resource: 'your-resource'
}
};
// Log in to get an authentication token
const authState = await authorize(config);
// Refresh token
const refreshedState = await refresh(config, {
refreshToken: authState.refreshToken,
});
Try not to put "scheme" option into app.json and use a redirectUrl like this.
<your.package.identifier>://oauthredirect
According to this AppAuth OAuthRedirect, AppAuth uses for scheme the android.package identifier. For example if your package.identifier is "your.company.app", use a redirectUrl like this: your.company.app://oauthredirect. It works for me.

Facebook App Invite with Cordova-plugin-facebook4

I am trying to implement Facebook app invite with this plugin in my ionic application. The implemented codes are following as below:
$scope.appInviteToFriend = function(user){
var url = "";
if (ionic.Platform.isAndroid())
{
url = "https://play.google.com/store/apps/details?id=com.example.application";
}
else if (ionic.Platform.isIOS())
{
url = "https://itunes.apple.com/nl/app/example-by-ionicapplication/id1983838444?l=en&mt=8";
}
var option = {
url: url,
picture : ""
};
facebookConnectPlugin.appInvite(
option,
function(obj){
if(obj) {
if(obj.completionGesture == "cancel") {
// user canceled, bad guy
} else {
// user really invited someone :)
}
} else {
// user just pressed done, bad guy
}
},
function(obj){
// error
console.log(obj);
}
);
}
When I executed these codes, the Facebook Invite Dialog opens and displayed app information correctly. But after click next button, select friend and also click send button, The error occurs. It says "Missing App Link URL. The app link used with this invite does not contain an Android or iOS URL.Developers are required to enter URl for at least one platform.". I've attached the error details with part of screenshot. Are these wrong the URLs which are store URL? How can I set the URLs?
You need to provide an App Link instead of a web URL. This link can be statically generated using Facebook's own tools, or you can generate them dynamically server-side. You can read more about these in the documentation.
Here's a tutorial that walks through setting up an Android app.

Ionic push not working - user not registered

I just had my first contacts with the ionic framework. I've worked with Phonegap and AngularJS before however, so it was not all that new to me.
I found out that there is this new feature to use Google Cloud Messaging push notifications in Ionic, through the Ionic Push feature (http://blog.ionic.io/announcing-ionic-push-alpha/).
Related lines of code from app.js
angular.module('starter', ['ionic','ionic.service.core', 'starter.controllers', 'starter.services'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleLightContent();
}
// enable push notifications
Ionic.io();
// enable users (http://docs.ionic.io/docs/user-quick-start)
// this will give you a fresh user or the previously saved 'current user'
var user = Ionic.User.current();
// if the user doesn't have an id, you'll need to give it one.
if (!user.id) {
user.id = Ionic.User.anonymousId();
// user.id = 'your-custom-user-id';
}
console.log('user-id:' + user.id);
//persist the user
user.save();
var push = new Ionic.Push({
"debug": true,
"onNotification": function(notification) {
var payload = notification.payload;
console.log(notification, payload);
},
"onRegister": function(data) {
console.log(data.token);
}
});
push.register(function(token) {
console.log("Device token:",token.token);
});
push.addTokenToUser(user);
console.log('token added to user');
});
})
Log from ionic serve
ionic $ 0 361081 log Ionic Core:, init
1 361083 log Ionic Core:, searching for cordova.js
2 361085 log Ionic Core:, attempting to mock plugins
3 361155 log user-id:1cc3d21c-b687-4988-b944-ad07b1a677c8
4 361158 log Ionic Push:, a token must be registered before you can add it to a user.
5 361159 log Ionic Push:, token is not a valid Android or iOS registration id. Cannot save to user.
6 361159 log token added to user
7 361160 log Ionic Push:, register
8 361160 error ReferenceError: PushNotification is not defined, http://localhost:8100/lib/ionic-platform-web-client/dist/ionic.io.bundle.min.js, Line: 2
9 361526 log Ionic User:, saved user
Any input is welcome, I am also more than happy to provide more information if needed.
EDIT 10/05/2015:
found out that dev_push = false only works on physical devices, not in browser
I tried to add token to user before even registering the user
I'm having the same problem, seems not many answers online at the moment.
but even on real device, it won't save the token to user.
I just had to decide go live without push first, then use ionic deploy to follow up.
also I think you have to put this line
push.addTokenToUser(user);
inside the register callback according to this doc
http://docs.ionic.io/docs/push-usage
You also need to declare 'ionic.service.push' as a dependency in your angular module if you'd like to use it.
angular.module('starter', ['ionic','ionic.service.core', 'ionic.service.push'])
I have it like this and it works:
Ionic.io();
var user = Ionic.User.current();
if (!user.id) {
user.id = Ionic.User.anonymousId();
// save our newly created user
user.save();
}
var push = new Ionic.Push({});
push.register(function (token) {
console.log("Got Token:", token.token);
// now we have token, so add it to user
push.addTokenToUser(user);
// don't forget to save user to Ionic Platform with our new token
user.save();
});
// set this user as current, so we can acess him later
Ionic.User.current(user);
Did you use this
ionic config set dev_push true-if testing in emulator or laptop
ionic config set dev_pushfalse - if testing on the phone
ionic push --google-api-key Your API Key
ionic config set gcm_key Project Number
Your token is the registration id that is unique for a particular device. That is sent to you by android.
Your Phone (With the API Key)---------> to Google's GCM
Google GCM (recognises it's you via your Project number and API key) -----> Oh it's you let me make a note of it. (Save a token id in it's DB and send's one to you.)
You get a registration id unique for your device(will change if an app is uninstalled).
You call your server say hey it's me your user. Please Notify me if you get something.
Server obliges, says, okay dude, I got this. Saves the registration id with your details probably your username in it's DB.
Now from Server.
I need to inform my users about a great deal(or an accident or something).
Pull up all targeted registration Id's from DB(maybe on some condition)
registrationIds.push(regId) //in a loop
and sender.send(message, registration, function(err, result){
});
Send to Google. Google see's oh only these many people(not all maybe) from this API Key need a notification. no Problem I will notify them and you receive a notification, my dear friend.
As mentioned in the link , Adding token to the $ionicUser is done by doing , user.addPushToken(pushToken); .
For this to work you should first configure the app not to use developement pushes by ,
ionic config set dev_push true
After initialising Ionic.io and Ionic.push , load the user or create one with a new random id ,
Ionic.io();
var push = new Ionic.Push();
Ionic.User.load(localStorage.id).then(function (user) {
Ionic.User.current(user);
pushFactory.register(push, user);
}, function (error) {
/*the user with that id is not present , so create one with a random id and register the push */
});
The push factory is defined as below,
function pushFactory() {
return {
'register': function (push, user) {
push.register(function (pushToken) {
user.addPushToken(pushToken);
user.save().then(function (answer) {
console.log('user saved'+answer);
})
})
}
}
}

Cordova/Phonegap facebook plugin An active access token must be used to query information

I am using https://github.com/Wizcorp/phonegap-facebook-plugin to connect my cordova Android app to Facebook.
I can login with:
facebookConnectPlugin.login(["email"],
fbLoginSuccess,
function (error) { alert("ERROR:" + JSON.stringify(error)); }
);
, logout even call facebookConnectPlugin.getLoginStatus and get:
userID
accessToken
expiresIn
sig
status
but when FB.api('/me', function(response){...}) is called, I receive
{error:
{
message: An active access token must be used to query information about the current user,
type: OAuthException,
code: 2500
}
}
Also this only happens when the app is built, not tested in browser.
Solved issue by manually giving FB.apicall a token with:
FB.api('/me?access_token='+userdata.authResponse.accessToken, function(response) {...
where userdata is the response of facebookConnectPlugin.getLoginStatus
I just don't understand why doesn't it provide token automatically in android app like it does in browser.
Send the access token and the data retrieving fields with the apiString
const fields = ['email', 'first_name', 'last_name', 'gender', 'birthday', 'picture.type(large)'];
const apiString = `me?access_token=${accessToken}&fields=${fields.join(',')}`;

WebApi: How to call Facebook Graph API by using an access token originated from the OAuth dialog

I have an ASP.NET WebApi 2.1 application with OAuth2 configured. I have and Android client where I can do authentication by using the following methods:
WebView approach (Web Api External Providers): redirect to https://www.facebook.com/dialog/oauth..., user do login there, FB asks for permissions, redirects to my url, catch it, access token got, done.
Facebook SDK approach: under the hood it does: redirect to https://graph.facebook.com/oauth..., user do login there, FB asks for permissions, redirects to my url, catch it, access token got, done.
The problem is, if I go with the WebView version, the token is good for authorizing user in my Web Api application, but I cannot call Graph API by using it, I receive OAuthException 190 (no subcode).
But if I do the SDK authorization, Graph API is accessible (through the Android Facebook SDK), but using the token I've got from it, Web Api authorization is not working, I get 401 by calling Authorization/UserInfo.
So my question are the above token types interchangeable somehow?
Any help would be greatly appreciated.
Sorry if that was not clear, I'm using Web Api w/ ASP.NET Identity 2.0 template, so OAuth plumbing code is already present there.
I was able to find an answer to my own question, let me share it with you.
So the problem is that the token I've got from the Facebook's OAuth dialog after the redirect is not the same token that my application can use to call Facebook Graph APIs in the name of the actual user. That Graph API token is reachable at the following point:
Assume you are using the mentioned template above, you can find App_Data/Startup.Auth.cs class with definition of a FacebookAuthenticationOptions instance. There you can catch the API token and can persist that into the database. For example:
var fbopts = new FacebookAuthenticationOptions
{
AppId = Global.Config.ExternalServices.FacebookAppID,
AppSecret = Global.Config.ExternalServices.FacebookAppSecret,
Scope = { "email", "user_friends", "publish_actions" },
Provider = new FacebookAuthenticationProvider
{
OnAuthenticated = async context =>
{
// This token will be OK for calling Graph API
string accessToken = context.AccessToken;
using (var tracer = Global.Tracer.CreateBuilder())
{
try
{
tracer.InformationLine("Storing Facebook OAuth token: " + accessToken);
string fbUserID = context.Identity.GetUserId();
string fbUserName = context.Identity.Name;
tracer.InformationLine("Facebook User ID: " + fbUserID);
tracer.InformationLine("Facebook User Name: " + fbUserName);
// Store it into the db
// assume Task StoreOAuthToken(string providerName, string providerKey, string accessToken) is defined
await StoreOAuthToken("Facebook", fbUserID, accessToken);
}
catch (Exception ex)
{
tracer.ErrorLine("Failed.", ex);
}
}
}
}
};
app.UseFacebookAuthentication(fbopts);
At this point you're gonna have a row in a table that consists of the following columns:
OAuthAccessToken.ProviderName
OAuthAccessToken.ProviderKey
OAuthAccessToken.AccessToken
Now you can provide an API to your consumers to have that API token for calling Graph API, like:
[Route("AccessTokens")]
[Authorize]
public async Task<List<OAuthAccessToken>> GetAccessTokens(string providerName = null)
{
var userID = User.Identity.GetUserId();
var q = from l in this.Context.AspNetUserLogins // Managed by ASP.NET Identity 2.0
from t in this.Context.OAuthAccessTokens // Stored by you with above code
where l.UserId == userID && t.ProviderName == l.LoginProvider && t.ProviderKey == l.ProviderKey
select t;
if (!string.IsNullOrEmpty(providerName)) q = q.Where(t => t.ProviderName == providerName);
return await q.ToListAsync();
}
So on Android after doing a Facebook login I have the Bearer token for my application's Web Api calls, and I can get my token for accessing Graph API by calling the action above.
Maybe there are easier methods for achieving the above. Please let me know if you find any.

Categories

Resources