CodeNameOne Google Plus OAuth2 - codenameone

Could anyone please help me with authenticating to Google Plus using OAuth2? I am able to get the authentication window to display, login and confirm my application with my account, but for some reason the action event is never fired. I get a screen saying Please copy this code, switch to your application and paste it there.
How do i get the action event to fire?
Thanks in advance.
Edit:
My code is as follows:
Hi Shai, thanks for the response, my code for the authentication is as follows:
Oauth2 auth2 = new Oauth2("https://accounts.google.com/o/oauth2/auth", "Client_Id", "urn:ietf:wg:oauth:2.0:oob or http://localhost", "openid", "https://accounts.google.com/o/oauth2/token", "Client_Secret");
Oauth2.setBackToParent(true);
auth2.showAuthentication(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() instanceof String) {
String token = (String) evt.getSource();
String expires = Oauth2.getExpires();
GOOGLE_TOKEN = token;
System.out.println("recived a token " + token + " which expires on " + expires);
//store token for future queries.
} else {
Exception err = (Exception) evt.getSource();
err.printStackTrace();
Dialog.show("Error", "An error occurred while logging in: " + err, "OK", null);
}
}
});
The "auth2.showAuthentication" works well, and allows you to pass through for the user to authorize the application but then once the user authorizes the application the "actionlistener" is never called, I never hit the callback. How can i force the callback to fire to return the token?

I have been struggling with the same issue. I finally found out that the problem lies in the setup of the WebBrowser inside Oauth2.createLoginComponent(): the onStart() handler waits for a URL starting with your supplied redirect URI, but this URL never appears. The final Google page, the one that brings the token, has a URL starting with "https://accounts.google.com/o/oauth2/approval?", not with the redirect URI.
According to Google's documentation the token will be supplied inside the page title, but this appears not to be the case with the native browser in CodeName One. I therefore ended up scraping the HTML document for an input with id="code", whose value is the token we're looking for. The scraping has to take place after the page has been loaded, i.e. in the onLoad() event, not in onStart().
Hope this helps, it worked for me.

Related

Angular sending access token to Asp.net Web API not working if the email address has a '+' in it

I have security working fine in an application, except when a user tries to login with a '+' in their email.
The access token looks fine (when the email contains a + it looks like this):
Bearer 8BGpt_KkEp-_6U5tUdKqK1xLCQBaWzHcxDT9RRKkbzoF2fHCUNhRL3U-fpLdQIuSXm8RcTOH4ZY3a0UZH6-6IgXxx_ojgyL26179JovRm5xQSZD7ANxLvvdU3ubfcpzSr4tw-sza37UaJh7xDFB8eH0NA9Djt7Ik8Ebxdin7u-n76InCulRAV6xMWgXfF9bwoU8MsV3lrh_zhnxYGnx3O7QUNQ740NUJLHJYH12rBth16CA1AXSF86rA5rUB7vJ7yK09k_FJTifyuldTeFHJHsyscnEIQxGozbf3x1cmZowkiK4Q1r8W0M8uz25m8j_tuMrWawTqYJNZiTuI9afW38WWQ4BRLkQF7TwoMOgZQ-f1K_3W8Zy3x-OsKdQS4i9CapvKe1utCscZVroByvyD9SvpILGiZGTjGD_zCAm8KerMPT5GNOb07kPGV_167PHEXm0TGaJbCelb5gLgXbMXv3GxBQLnYIfPUXCBaKx4UFkY8kFMPs9MxFcGY81p67rfnjeswBZ3PW6fDFTf9U_I8g
However, when I try to send a secure request with this access token, I get the response:
status: 401
"{"Message":"Authorization has been denied for this request."}"
As said above, it works without any issue if I remove the plus. This seems to be a Wep API issue rather than an Angular issue.
I found that the methods encodeUrl and decodeUrl to not stop the space from being change to a plus. I have tried the following in the c# code to switch the space to a plus:
var registerEmail = model.email.Replace(' ', '+');
This is used in both the login and register actions.
Perhaps it is not possible to use a + in an email in OAuth in Web API 2?
It seems to be a bug in asp.net roles. I am not sure of a clear solution. However, for the time being, encoding the username as follows before storing it on register and when logging in:
public static class UsernameEncodingService
{
public static string returnEncodedUsername(string email)
{
var emailAsLower = email.ToLowerInvariant();
var encodedEmail = Base64Encode(emailAsLower);
var encodedEmailWithoutEquals = encodedEmail.Replace("=", "213");
var encodedEmailWithoutPlus = encodedEmailWithoutEquals.Replace("+", "214");
return encodedEmailWithoutEquals;
}
private static string Base64Encode(string plainText)
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
}

Unity/Android ServerAuthCode has no idToken on Backend

I have an unity app and use the google-play-games plugin with google *.aar versions 9.4.0. I lately changed my Backend (Google App Engine) from php to java. My problem is the following: in php the serverauthcode is used to get the users data (in JWT format) - it was working fine. So I changed to a Java servlet and I am failing since 2 days to get a valid idtoken. I am able to recieve the server auth code from my app and a valid token response is made by GoogleAuthorizationCodeTokenRequest (see code snippet). Unfortunately it does not contain any idtoken content but a valid auth_token. So I can not get the user id to identifiy the user. When I call tokenResponse.parseIdToken(); it is failing with a NullPointerException.
servlet code (authCode is the serverAuthCode I send from the play-games-plugin inside Unity to my GAE):
// (Receive authCode via HTTPS POST)
// Set path to the Web application client_secret_*.json file you downloaded from the
// Google Developers Console: https://console.developers.google.com/apis/credentials?project=_
// You can also find your Web application client ID and client secret from the
// console and specify them directly when you create the GoogleAuthorizationCodeTokenRequest
// object.
String CLIENT_SECRET_FILE = "/mypath/client_secret.json";
// Exchange auth code for access token
GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(
JacksonFactory.getDefaultInstance(), new FileReader(CLIENT_SECRET_FILE));
GoogleTokenResponse tokenResponse =
new GoogleAuthorizationCodeTokenRequest(
new NetHttpTransport(),
JacksonFactory.getDefaultInstance(),
clientSecrets.getDetails().getTokenUri(),
clientSecrets.getDetails().getClientId(),
clientSecrets.getDetails().getClientSecret(),
authCode,
REDIRECT_URI) // Specify the same redirect URI that you use with your web
// app. If you don't have a web version of your app, you can
// specify an empty string.
.execute();
String accessToken = tokenResponse.getAccessToken();
// Get profile info from ID token -> HERE IT THROWS AN EXCEPTION.
GoogleIdToken idToken = tokenResponse.parseIdToken();
GoogleIdToken.Payload payload = idToken.getPayload();
String userId = payload.getSubject(); // Use this value as a key to identify a user.
String email = payload.getEmail();
boolean emailVerified = Boolean.valueOf(payload.getEmailVerified());
String name = (String) payload.get("name");
String pictureUrl = (String) payload.get("picture");
String locale = (String) payload.get("locale");
String familyName = (String) payload.get("family_name");
String givenName = (String) payload.get("given_name");
the token response looks like (its invalid now):
{
"access_token" : "ya29.CjA8A7O96w-vX4OCSPm-GMEPGVIEuRTeOxKy_75z6fbYVSXsdi9Ot3NmxlE-j_t-BI",
"expires_in" : 3596,
"token_type" : "Bearer"
}
In my PHP GAE I always had a idToken inside this constuct which contained my encrypted data. But it is missing now?! So I asssume I do somthing differently in Java or I made a mistake creating the new OAuth 2.0 Client on the google console.
I checked the accessToken manually via:
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=ya29.CjA8A7O96w-vX4OCSPm-GMEPGVIEu-RTeOxKy_75z6fbYVSXsdi9Ot3NmxlE-j_t-BI
{
"issued_to": "48168146---------.apps.googleusercontent.com",
"audience": "48168146---------.apps.googleusercontent.com",
"scope": "https://www.googleapis.com/auth/games_lite",
"expires_in": 879,
"access_type": "offline"
}
Is there something I do not see? Help is very much appreciated...
I found a root cause discussion inside the unity plugin "play-games-services" on github:
https://github.com/playgameservices/play-games-plugin-for-unity/issues/1293
and
https://github.com/playgameservices/play-games-plugin-for-unity/issues/1309
It seems that google switching their authentication flow. In the given links they are talking about adding the email scope inside the plugin to get the idtoken again. I'll try that in the next days and share my experience.
Here is a good explaination about what happens:
http://android-developers.blogspot.de/2016/01/play-games-permissions-are-changing-in.html
If you do what paulsalameh said here (Link to Github) it will work again:
paulsalameh: Sure. After you import the unitypackage, download NativeClient.cs and
PlayGamesClientConfig.cs from my commits (#1295 & #1296), and replace
them in the correct locations.
Afte that "unity play-services-plugin" code update you will be able to add AddOauthScope("email") to PlayGamesClientConfiguration, which allows your server to get the idtoken with the serverAuthCode again...
Code snippet from Unity:
PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder()
.AddOauthScope("email")
.AddOauthScope("profile")
.Build();
Now I am back in business:
{
"access_token" : "ya29.Ci8..7kBR-eBdPw1-P7Pe8QUC7e_Zv7qxCHA",
"expires_in" : 3600,
"id_token" : "eyJhbGciOi......I1NiE0v6kqw",
"refresh_token" : "1/HlSZOo......dQV1y4E",
"token_type" : "Bearer"
}

refreshToken is null

I used DREdit app's Oauth code to get accessToken and refreshToken for my app and i am getting the accessToken but refreshToken is coming null always.
I tried to print the values in the code which comes like below
authorization URL:https://accounts.google.com/o/oauth2/auth?access_type=offline&approval_prompt=force&client_id=651991573332.apps.googleusercontent.com&redirect_uri=http://www.sakshum.org/GoogleOauth&response_type=code&scope=https://www.googleapis.com/auth/drive.file%20https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/userinfo.profile
This code already has access_type=offline which I found not having in the url was the cause in some cases. Please advise what else could be wrong here.
The log prints as follows on appEngine
[s~sakshumweb-hrd/3.368699522239285323].<stdout>: Code:4/XQ1sR1Pu5VHDqGbG9iJO10bXVCCE.Qn-L1XwrBVYaEnp6UAPFm0EmSoCXfwI
W 2013-07-10 20:20:16.294
com.google.api.client.googleapis.services.AbstractGoogleClient <init>: Application name is not set. Call Builder#setApplicationName.
I 2013-07-10 20:20:16.536
[s~sakshumweb-hrd/3.368699522239285323].<stdout>: id:113470899999229420779
I 2013-07-10 20:20:17.936
[s~sakshumweb-hrd/3.368699522239285323].<stdout>: access token:ya29.AHES6ZSP7MXaaUhMz4RO7Jm3Zkh_s1zUxJyzW_6IvfADaQ
I 2013-07-10 20:20:17.936
[s~sakshumweb-hrd/3.368699522239285323].<stdout>: refresh token:null
Refresh tokens are only issued on the initial authorization (whenever the consent screen is shown.) If you find you're in a state where you don't have a saved refresh token for a user, you can ask for reauthorization with the added query parameter prompt=consent. The user will be asked to re-authorize and a new refresh token will be generated.
After your link you get authorization code. For instance:
https://accounts.google.com/o/oauth2/auth?access_type=offline
&approval_prompt=auto
&client_id=[your id]
&redirect_uri=[url]
&response_type=code
&scope=[access scopes]
&state=/profile
then if in future you are going to have access to drive you need refresh token (you can every time request auth token - redirecting to google and etc... but it's not good way. after first usage, you should save Credentials in Database with User UID (for instance, it may be mail). So if you need to have access to the drive in the feature you do this:
static Credential exchangeCode(String authorizationCode)
throws CodeExchangeException {
try {
GoogleAuthorizationCodeFlow flow = getFlow();
GoogleTokenResponse response =
flow.newTokenRequest(authorizationCode).setRedirectUri(REDIRECT_URI).execute();
return flow.createAndStoreCredential(response, null);
} catch (IOException e) {
System.err.println("An error occurred: " + e);
throw new CodeExchangeException(null);
}
}
As I guess you also want to get url of the file which is in the Google Drive. when you get files - thee the documentation, then you will find download methids in com.google.api.services.drive.model.File object. read documentations

How do I use the Google API Explorer to test my own App Engine Endpoints using OAuth?

I have an Endpoints API deployed on App Engine. I have no problem using the Google API Explorer to make requests to API methods that do NOT require being logged in. The URL I'm using for that is:
https://developers.google.com/apis-explorer/?base=https://[MY_APP_ID].appspot.com/_ah/api
Where I am stuck is calling API methods that require the user to be logged in, such as this one:
#ApiMethod(name = "config.get",
clientIds = {"[MY_CLIENT_ID].apps.googleusercontent.com", "com.google.api.server.spi.Constant.API_EXPLORER_CLIENT_ID"},
audiences = {"[MY_APP_ID].appspot.com"},
scopes = {"https://www.googleapis.com/auth/userinfo.email"})
public Config getConfig(User user) throws OAuthRequestException {
log.fine("user: " + user);
if (user == null) {
throw new OAuthRequestException("You must be logged in in order to get config.");
}
if (!userService.isUserAdmin()) {
throw new OAuthRequestException("You must be an App Engine admin in order to get config.");
}
...
On the API Explorer there's a switch top right that, when clicked, allows me to specify scopes and authorise. I'm doing that with just the userinfo.email scope checked. It makes no difference. The response I get from my call is:
503 Service Unavailable
- Show headers -
{
"error": {
"errors": [
{
"domain": "global",
"reason": "backendError",
"message": "java.lang.IllegalStateException: The current user is not logged in."
}
],
"code": 503,
"message": "java.lang.IllegalStateException: The current user is not logged in."
}
}
Back when Endpoints was in Trusted Tester phase, I remember there being a manual step in the OAuth2 Playground to get an ID token instead of an access token or some such thing. If that is still required, any mention of that seems to have disappeared from the Endpoints docs now and I see now way to swap out tokens in the API Explorer either.
I see you've got "com.google.api.server.spi.Constant.API_EXPLORER_CLIENT_ID" in quotes. If that's not a typo in your transcription to Stack Overflow, that's a problem. The value is already a string, so you're just passing in the text com.google.api.server.spi.Constant.API_EXPLORER_CLIENT_ID (not the actual client ID) as the whitelisted scope. That won't work. Try this instead:
#ApiMethod(name = "config.get",
clientIds = {"[MY_CLIENT_ID].apps.googleusercontent.com", com.google.api.server.spi.Constant.API_EXPLORER_CLIENT_ID},
audiences = {"[MY_APP_ID].appspot.com"},
scopes = {"https://www.googleapis.com/auth/userinfo.email"})
Edit: isUserAdmin is unsupported within Endpoints, and is likely a secondary cause of error. I'd suggest filing a feature request for supporting this method on the provided User object (we likely won't provide support for the user service itself, so it's separate from OAuth login.)
I don't know when this was introduced, but if you use OAuth2, instead of UserService.isUserAdmin() you can use OAuthServiceFactory.getOAuthService().isUserAdmin(EMAIL_SCOPE) where EMAIL_SCOPE is "https://www.googleapis.com/auth/userinfo.email".
This makes it easy to use the old OpenId or OAUth2:
boolean isAdmin = false;
try {
isAdmin = userService.isUserAdmin());
} catch (IllegalStateException e1) {
try {
isAdmin = OAuthServiceFactory.getOAuthService().isUserAdmin(EMAIL_SCOPE);
} catch (Exception e2) {}
}
The original question was asked several years ago, but maybe this will help others.

On Authentication for google contacts, Callback from google returned in a new session

I am using GAE + GWT + Guice , Doing following for Google contacts API. (see code)
When Google service redirects back to application URL with Token,
it creates new session, as URL was called from Google server not client's browser.
Two questions
1. Is it correct behavior? If not, How can I correct it?
2. What is the preferred way to store/use token for requesting user?
Request Servlet (GWT RPC)
public String getAuthLink() {
String next = "http://localhost:8888/serviceCallback?service=GMAIL";
String scope = "https://www.google.com/m8/feeds/";
boolean secure = false;
boolean session = true;
return AuthSubUtil.getRequestUrl(next, scope, secure, session);
}
#Override
public boolean isAuthenticated(ServiceProviderKey serviceProviderKey) {
//SESSION PRINT A
System.out.println("Session: " + getThreadLocalRequest().getSession().getId());
//SOME CODE
}
Callback servlet
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
String authToken = req.getParameter("token");
String sessionToken = AuthSubUtil.exchangeForSessionToken(authToken, null);
//SESSION PRINT B
System.out.println("Session: " + req.getSession().getId());
req.getSession().setAttribute("token", sessionToken);
}
EDIT
I understood that receiving different session is correct behavior, so now I want to figure out, for which user (session in my app) I have received callback for. so I though of passing session_id/user_id to callback_uri but it is not allowed, callback URI must match with registered callback URI in Google API console. I am really stuck.. Looks like only I am having this particular issue, Any idea?

Resources