accountmanager refresh token(offline access) - android

I use google login through account manager in my android app. I can get accesstoken which I send to server and server can create/login new user. Accesstoken is valid only 3600seconds. Problem is that server can not update user's info after this time expires. Web app requires check user's info periodically.
How can I get authentication token and refresh token from android account manager so than server can use refresh token to update data periodically? I don't want use login through webview in android app.
Thanks

This is now possible: https://developers.google.com/+/mobile/android/sign-in#server-side_access_for_your_app
You request a one-time authorisation code, send it to your server and your server exchanges it for an access token and refresh token.

Currently you can't, which I'm sure is not the answer you're hoping for, sorry about that! If you have a web sign in, you can use the hybrid flow to get a refresh token on the server as well (see https://developers.google.com/+/web/signin/server-side-flow), but there's no way of retrieving a code as part of the Android or iOS flows.
If this is something that you need for you use case, could you file a feature request on here: https://code.google.com/p/google-plus-platform/issues - we are actively looking at the number of stars on that to gauge demand for various features.

Google Authorization process through account manager:
Email id can be got from
AccountManager accountManager = AccountManager.get(getApplicationContext());
Account[] accounts = accountManager.getAccountsByType("com.google");
String emailID = accounts[0].name; // you can retrieve using google account chooser way also
These lines should be run in separate token(not in UI thread).
String scope = "oauth2:https://www.googleapis.com/auth/userinfo.profile https://gdata.youtube.com";
String accessToken = GoogleAuthUtil.getToken(mContext, emailID, scope);
save the the accessToken and use for your api access.
After one hour (i.e. 3600 seconds), we need to refresh the access token. But now google is not supporting access after one hour. We have to restart the application and use the following lines to get access token.
String scope = "oauth2:https://www.googleapis.com/auth/userinfo.profile https://gdata.youtube.com";
String accessToken = GoogleAuthUtil.getToken(mContext, emailID, scope);
This background thread will always run in background in while loop

Related

How to use facebook login to access data from backend server in Android app?

I am working on an app in which I have to use facebook login for accessing data from my backend server. I have search on this and got that:
First, the user will enter username and password of facebook then the request goes to server.
If user authenticated then fetch access token of user.
Send this access token on server.
The server will verify this access token.
I have successfully connected my app with facebook i.e, now user can logged from my app to facebook. But I don't now how can I get the access token of user and also how I can verify this access token on server.
Can you provide me some sample code for this. Please help me I am stuck in it from a long time.
I'm not sure if it is best practice, but this is how I do it.
When you log a user in Android on the client device via any of the SDKs, you get an user access token. The token can be accessed as follows
AccessToken token = AccessToken.getCurrentAccessToken();
if (token != null) {
Toast.makeText(getActivity(), token, Toast.LENGTH_LONG).show();
}
You can then pass this token to the backend as a POST variable:
'access_token': '32b409xceBV78d2932b409xceBV78d29'
Using a backend SDK, you can get the user info again. Here's a example in python
facebook_graph = facebook.GraphAPI(access_token)
If the email and fbid match the user information stored in your database, you grant access:
user = get_user(email=facebook_graph['email'], fbid=facebook_graph['fbid'])
login(request, user)
To access the data of the facebook user you have to take permissions and the following link may be useful for you. Just check it out...
https://developers.facebook.com/docs/howtos/androidsdk/3.0/fetch-user-data/

Use Android AccountManager to do AppEngine login through UserService

I'm using Google AppEngine, and I'm using their UserService class to handle user accounts and logging in. I don't need to access any information about their account - I'm just using it to differentiate users.
Now the website is mostly just a backend. I'm using an Android app for the frontend. I know you can access Google user accounts on the device using the AccountManager. It's definitely the safest way to get a user to log in. And I got that much to work.
Where I'm stuck is passing the login information from the Android app to the AppEngine website. From what I've ready I should be using OAuth, and I see the walkthrough here for using it with Google APIs, but I don't need to access an API, just to log in. I've been able to acquire an Authentication Token in the app, but I'm not sure how to pass it to the website, or if that's even the right direction. Should I be using a specific OAuth login on the server, like this guy?
Any help would be greatly appreciated!
Here's the relevant code:
Server (GAE):
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
if (user == null) {
resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
return;
}
Client (Android):
AccountManager am = AccountManager.get(this);
Account[] accounts = am.getAccountsByType("com.google");
Bundle options = new Bundle();
am.getAuthToken(
accounts[0], // Account retrieved using getAccountsByType()
"Manage your tasks", // Auth scope
options, // Authenticator-specific options
this, // Your activity
new OnTokenAcquired(), // Callback called when a token is successfully acquired
new Handler(new OnError()));
//Now what!?
This blog post covered exactly what I needed.
For two alternate (and in my opinion less than ideal) solutions, check out this thread: Webservice credentials - OpenID/Android AccountManager?

Facebook Single Sign On to register or log-in in server (Android and Ios)

We are implementing a project where the users post and get some information from a server. The scenario is that the user can create account/login both manually (giving email and password) and with facebook credentials using SSO. I implement mostly the Android part, but my questions are general.
Let’s say that I have a button where SSO is called prompting the user to give his credentials. So in order to create account what should I send to the server? Get the FB email of the user and set as password the Access Token that I received? Is that Access Token unique and permanent for every FB account, meaning the each time I use the same FB credentials I get the same Access Token?
Is there any additional work that needs to be done on the server side? Or can the server handle the users that use their FB accounts similarly as it handles the others?
Every clarification will be really helpful. Thank you in advance!
Are you using the Facebook Android SDK? If so, manual login (with user email/password) and SSO (via the Android Facebook app) are very similar, in particular with respect to token handling.
For example if you check out the example in the SDK (at sdk\examples\simple\src\com\facebook\android) you will see that the code does something like the following (split between three files).
private static final String TOKEN = "access_token";
private static final String EXPIRES = "expires_in";
private static final String KEY = "facebook-session";
Facebook session = new Facebook(APP_ID);
SharedPreferences savedSession = context.getSharedPreferences(KEY, Context.MODE_PRIVATE);
session.setAccessToken(savedSession.getString(TOKEN, null));
session.setAccessExpires(savedSession.getLong(EXPIRES, 0));
if (session.isSessionValid()) {
session.authorize(mActivity, mPermissions, new LoginDialogListener());
}
So you have to save the session token in SharedPreferences after each successful login (that is also in the example), but the token handling and login (authorize()) is the same for both manual and SSO login (depending on the activityCode parameter).
The token has a expiration timestamp, I guess the easy way is to generate the user account with the data fb will send you and store the fb token and expiration date as user attributes.

Facebook auth token exchange

Is it possible to authenticate the user on server side using auth token retrieved by Android applicaton from Facebook?
In other words Android application uses SSO and obtain auth token. Then sends this token to backend application deployed on Google App Engine. Then backend application verifies the user against Facebook using the token.
I guess it's not feasible because retrieved token can be used only by Android application, but who knows? Maybe it may be reused somehow?
The Token you get from Android API can be sent to your server, who can check the validity of the token by querying the graph ( using /me?auth_token=.... for example).
The problem is that the same token can be used by any third party - it's not client specific - and so if you base server identification based on that, you have a problem (since a third app could use its user token and get authenticated by you). I am trying to find a way to solve this issue, but I don't have good ideas yet...
Facebook actually has an Android SDK that lets you do this. Information can be found here.
Yes you can. A valid access token is a valid access token. The Graph API does from where the token came, but only that the token has the appropriate permissions to access that portion of the graph api. Keep in mind, though, that the token is only valid for 24 hours from the time of its issuance. (is that really a word?) From the time it is issued?
When using facebook android sdk with SingleSignOn (SSO), the access token format actually changed.
Instead of getting traditional auth token which contains userid & session key as a part of authToken
now we get a different format of authToken
As Facebook Devs are still in process to support there rest apis with newly formated access token
meanwhile we can disable the SSO on android facebook sdk by changing DEFAULT_AUTH_ACTIVITY_CODE to -1 from 32665 (in Facebook.java)
This will invoke Traditional dialouge for granting acess token and in return you'll get access token which will contain session key in it.
Those who are looking for generating secure session key you need to add your own method in Facebook.java like
public String getSessionSecret(String accessToken) throws MalformedURLException, IOException
{
Bundle b = new Bundle();
b.putString("method", "auth.promoteSession");
b.putString("access_token", accessToken);
b.putString("session_key_only", "true");
String response = request(b);
return response;
}

Using authToken for Google Health Data

We have developed and published an app for Google Health. Now we want to avoid every time logging into the gmail account by asking username and password.
So as to do this i have heard that I can have following options.
1. OAuth
2. Account Manager
3.
The problem with OAuth is that it will go via Android -> Web App -> Health path so i will need to develop an web app as well which we dont wish to do it right now.
So I am trying to use Account Manager, here is my code with which I could get list of accounts and an valid authToken for the selected account.
AccountManager mgr = AccountManager.get(getApplicationContext());
System.out.println("Got account manager");
Account[] accts = mgr.getAccounts();
}
Account acct = accts[0];
AccountManagerFuture<Bundle> accountManagerFuture = mgr.getAuthToken(acct, "android", null, this, null, null);
Bundle authTokenBundle = accountManagerFuture.getResult();
System.out.println("Account name "+accts[0].name);
String authToken = authTokenBundle.get(AccountManager.KEY_AUTHTOKEN).toString();
System.out.println("Got token:"+authToken);
But now I am confused about how to use this token to access the health data.
For getting the demographic feed we used the following code,where we explicitly made user to login into our application.
String queryURL = "https://www.google.com/health/feeds/profile/ui/" + profileId +"/-/DEMOGRAPHICS";
getDemoGrInfoQuery = new Query(new URL(queryURL));
Feed dempGrResultFeed;
globals = new Globals();
dempGrResultFeed = healthService.query(getDemoGrInfoQuery, Feed.class);
And thus we used to get the Feed using the URL.
And now I want to skip the login process and use the above authToken for retrieving the feed. How can this be done?
Any help would be really appreciated!!!
Thanks in advance,
As the standard OAuth procedure is supposed to work, you open the OAuth URL in a WebView (or anything similar) with all the required parameters, users provide Google (not your app) with their user name and password, then google gives you a token which you can use for your future communications.
This way the user doesn't have to give you their login credentials. They give it only to google, and google gives you a token which will authenticate your app every time you use it.
I think you should be good to go with this, since it requires you to open a WebView only once, unless the user logs out of google using your application or denies access to your application.
After getting the token, you just start polling google with that token and never ask user for their login credentials. quite seamless.
UPDATE
After our conversation in chat, let me tell you that you'll have to register an application with google, which will give you an appID, this appID will be used by your Android app to tell google that it is requesting permission on behalf of the Application which this appID refers to.
UPDATE 2
open the Google OAUth with all the parameters, google will give you a code
use that code and create a POST request again to google, and google will now return a long lasting AccessToken
You can then use this AccessToken in all your future communications

Categories

Resources