The online reference for Google APIs for Android, shows a public method summary for the Games class which includes:
static PendingResult<Games.GetTokenResult> getGamesAuthToken(GoogleApiClient apiClient)
But the latest release available (8.4.0) does not include this method. I use this to get the APIs:
dependencies {
compile 'com.google.android.gms:play-services:8.4.0'
}
Where is Games.getGamesAuthToken?
This is actually a documentation problem. getGamesAuthToken() has been removed because it was not as secure as it needs to be.
For reference, you can read http://android-developers.blogspot.com/2016/01/play-games-permissions-are-changing-in.html
The best way to handle this is to:
After the player is authenticated on the device:
Get an auth code to send to your backend server:
GetServerAuthCodeResult result =
Games.getGamesServerAuthCode(gac, clientId).await();
if (result.isSuccess()) {
String authCode = result.getCode();
// Send code to server.
}
On the server, exchange the auth code received for a token by
making an RPC to https://www.googleapis.com/oauth2/v4/token to exchange the auth code for an access token.
You’ll have to provide the server client ID, server client secret (listed in the Developer Console when you created the server client ID), and the auth code.
See more details here: https://developers.google.com/identity/protocols/OAuth2WebServer?utm_campaign=play games_discussion_permissions_012316&utm_source=anddev&utm_medium=blog#handlingresponse.
Once you have the access token, the player's ID is retrieved using:
www.googleapis.com/games/v1/applications/<app_id>/verify/ using the access token.
Pass the auth token in a header as follows:
“Authorization: OAuth ”
The response value will contain the player ID for the user. This is the correct player ID to use for this user.
This access token can be used to make additional server-to-server calls as needed.
Related
I've been trying to add Google Sign-In in Android but have a couple of doubts.
From the Android documentation Integrate google sign in android
In the server side authentication part Client Id is required which is OAuth 2.0 web application client ID for your backend server.
From android's documentation:
Get your backend server's OAuth 2.0 client ID
If your app authenticates with a backend server or accesses Google APIs from your backend server, you must get the OAuth 2.0 client ID that was created for your server. To find the OAuth 2.0 client ID
From my understanding the flow would be:
Android app will get the auth code from google which will be passed to the backend.
The backend will get the access token with the auth code from the android app and the client secret.
With the acess token we get the user's information and the access token is saved in the database.
My doubts are:
I read somewhere on StackOverflow that we need to create two OAuth client one for Android and one for Web Application. Is this True?
Django Rest Auth Login View need to have one redirect_url defined but I don't understand what would be the redirect_uri in case of Android device or we need to pass this URL while getting the auth code from Google.
On OAuth Playground I put my backend's client id and client secret and got the auth code and when I passed this auth code to my login view I was getting the redirect_uri_mismatch but If I put redirect_url = 'developer.google.com' It works, I guess the auth code contains host information from where it is generated that's why this should be the same as redirect_url in my rest-auth view but then for android what it should be?
Here is my Google Login View.
class GoogleLogin(SocialLoginView):
adapter_class = GoogleOAuth2Adapter
client_class = OAuth2Client
callback_url = 'localhost:8000' # What this should be?
Please ask for more information If I forgot to put any.
I am using this
django-rest-auth
Some helpful link -
https://github.com/Tivix/django-rest-auth/issues/262#issuecomment-256562095 # It says callback URL could be a fake one but I get redirect_uri_mismatch
So Finally, I figured it out, Answering my own question so someone might find this helpful.
Yes, you need two client id one for your Android device and one for your web application.
Just add http://localhost:8000/accounts/google/login/callback/ as callback_url in the GoogleLoginView and put the same in your Google developer console.
I don't know exactly if the auth code generated by the Android contains any host information or not but it seems as long as the callback URL you added in the login view class and in google developer console is the same it will work.
Your Google sign in view should look like this.
class GoogleLogin(SocialLoginView):
authentication_classes = (JSONWebTokenAuthentication,)
adapter_class = GoogleOAuth2Adapter
callback_url = 'http://localhost:8000/accounts/google/login/callback/'
client_class = OAuth2Client
Note: You only need callback_url and client_class in case where you are passing the auth code to this view but if in you are passing the access_token then callback_url and client_class is not necessary.
As the title says, I'm trying to use the Google Sign-In API with a Spring Boot backend server, as described here.
Just to describe the context, the Spring backend is basically a resource+authentication server, that is currently providing Oauth2 authentication to a second spring boot application containing the frontend website, via Google SSO or simple form login (similar to what's described here).
My original idea was to mimic the #EnableOauth2Sso annotation by simply providing an access token to the android app and attach it to every request as "Bearer ".
Using the user credentials for this was pretty straightforward: I simply make a request to the server at "/oauth/token", using those credentials inserted by the user as authentication and I correctly receive the access token.
Now, I have absolutely no idea on how to build a similar procedure with the Google API in Android. The tutorial page I linked before describes how to get a token ID and how the server should validate it, but after that I don't know what to do.
So far I've managed to add a filter to the security chain that simply checks the token like this:
private Authentication attemptOpenIDAuthentication(#NonNull String tokenString){
String clientId = authServices.getClientId();
GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(transport, factory)
.setAudience(Arrays.asList(clientId, androidClient))
.build();
try {
GoogleIdToken token = verifier.verify(tokenString);
if (token != null) {
return authServices.loadAuthentication(token.getPayload());
} else {
throw new InvalidTokenException("ID token is null");
}
} catch (GeneralSecurityException | IOException e) {
throw new BadCredentialsException("Could not validate ID token");
}
}
This manages indeed to create an Authentication object, but how can I generate an access token after the authentication filtering?
To recap, so far I've got:
The Android app successfully retrieves the Google token ID and sends it to the server
The server sucessfully intercepts the request and validates the token
I'm basically missing the third point where I return a proper access token to the Android client.
Here you are a simple scheme to better understand the situation:
Is there any other way to validate the token and get an access token from the server, or should I completely change the authentication procedure on Android?
As far as I can tell: Yes, you need an access token from the server. If I understand this correctly, a webapp is already authenticated via Oauth on your backend, so the procedure is similar here: Load the user with the google-ID and generate a token. In my application I used a JWT which is valid for 30 days. If the token expires, the Google authentication in the app is usually still valid, so the token can be renewed using the Google ID. With Oauth you can also send a refresh-token directly.
It is important that the app always checks the Google authentication first and only in a second step that of the backend.
For the Authentication process on the backend u may need to manually implement a dedicated securityConfiguration for this. Have a look at the jhipster project, they implemented a custom jwt-authentication which may give you an idea how it works.
I'm using the Google Speech API in an Android app. The README states:
In this sample, we load the credential from a JSON file stored in a raw resource folder of this client app. You should never do this in your app. Instead, store the file in your server and obtain an access token from there.
Are there any samples regarding how to properly obtain an access token for a production app?
From what I've gathered, it seems that I can use Application Default Credentials provided via Compute Engine or GAE, but I have no idea how to actually respond with an access token to my app.
I'm the author of the sample.
Here's the part that should be on the server side. Basically, you have to store the JSON file securely on your server side, and fetch a new access token when you get a request from your mobile app. Mobile app should always talk with your server to get an access token. This way, you don't need to put your service account key in the APK.
// In response to a request from a mobile client
// Open the JSON file stored on the server side.
final InputStream stream = ...;
try {
// Initialize the credentials
final GoogleCredentials credentials =
GoogleCredentials.fromStream(stream)
.createScoped(SCOPE);
// Fetch a new access token.
final AccessToken token = credentials.refreshAccessToken();
// Return the token to the mobile app.
} catch (IOException e) {
// Maybe report this as an HTTP error.
}
If you don't use Java on your server side, you can find a client library for the language you use at Google Cloud Client Libraries.
Refer to Google Cloud Platform Auth Guide for basics about how to send requests from your backend to the API.
For Android, you might instead want to use the Android sample for Google Cloud Speech as the Cloud client library does not currently focus on Android support.
I've been having problems implementing Google Play Services login on my android app and passing the authorisation code to my backend server, so the server will exchange the code for access token and refresh token.
First let me write a few lines what has already been tried/read:
on code.google.com/apis/console I've created a new project, with two clients (WEB client and Android installed client)
read articles on https://developers.google.com/+/mobile/android/sign-in#cross-platform_single_sign_on and http://android-developers.blogspot.com/2013/01/verifying-back-end-calls-from-android.html
Next I wrote simple android app (based on Google Play Services sample auth app) and a simple python code using gdata (using web service client_id and secret).
On android app I first used four scopes delimited with space and got a token. If I use this token in my python code I always get {'error_message': 'unauthorized_client'}.
Then I tried to change the scope to this values and always got invalid scope error.
oauth2:server:client_id:server-client-id:api_scope:scope1 scope2
audience:server:client_id:server-client-id:api_scope:scope1 scope2
oauth2:audience:server:client_id:server-client-id:api_scope:scope1 scope2
For server-client-id I used the client_id of web server client, android client, other client
Please can anyone help me with this problem.
Thanx
Here is the code for python backend
import gdata
import gdata.gauth
CLIENT_ID = 'client_id'
CLIENT_SECRET = 'secret_id'
SCOPES = ["https://www.google.com/m8/feeds", "https://mail.google.com", "https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email"]
USER_AGENT = 'my-app'
token = gdata.gauth.OAuth2Token(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, scope=' '.join(SCOPES), user_agent=USER_AGENT)
print "token ", token
print token.generate_authorize_url(redirect_url='urn:ietf:wg:oauth:2.0:oob')
try:
print token.get_access_token("token")
except Exception, e:
print e
print e.__dict__
You are retrieving an authorization code, not an access token. These are two different things.
Authorization codes can be used in your server side to get an access token. They are not access tokens and cannot be used as such.
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;
}