Search in sources :

Example 1 with Oauth2

use of com.codename1.io.Oauth2 in project CodenameOne by codenameone.

the class GoogleImpl method nativeLoginImpl.

private void nativeLoginImpl(final GoogleApiClient client) {
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(client);
    AndroidNativeUtil.startActivityForResult(signInIntent, RC_SIGN_IN, new IntentResultListener() {

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
            if (requestCode == RC_SIGN_IN) {
                final GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
                if (result.isSuccess()) {
                    // Signed in successfully, show authenticated UI.
                    GoogleSignInAccount acct = result.getSignInAccount();
                    String displayName = acct.getDisplayName();
                    String acctId = acct.getId();
                    String email = acct.getEmail();
                    String requestIdToken = acct.getIdToken();
                    Set<Scope> grantedScopes = acct.getGrantedScopes();
                    String code = acct.getServerAuthCode();
                    String scopeStr = scope;
                    System.out.println("Token is " + acct.getIdToken());
                    if (acct.getIdToken() == null && clientId != null && clientSecret != null) {
                        Log.p("Received null ID token even though clientId and clientSecret are set.");
                    }
                    // otherwise we'll set the token to null.
                    if (clientId != null && clientSecret != null && requestIdToken != null && code != null) {
                        ConnectionRequest req = new ConnectionRequest() {

                            @Override
                            protected void readResponse(InputStream input) throws IOException {
                                Map<String, Object> json = new JSONParser().parseJSON(new InputStreamReader(input, "UTF-8"));
                                if (json.containsKey("access_token")) {
                                    setAccessToken(new AccessToken((String) json.get("access_token"), null));
                                    Display.getInstance().callSerially(new Runnable() {

                                        @Override
                                        public void run() {
                                            callback.loginSuccessful();
                                        }
                                    });
                                } else {
                                    setAccessToken(new AccessToken(null, null));
                                    Log.p("Failed to retrieve the access token from the google auth server.  Login succeeded, but access token is null, so you won't be able to use it to retrieve additional information.");
                                    Log.p("Response was " + json);
                                    Display.getInstance().callSerially(new Runnable() {

                                        @Override
                                        public void run() {
                                            callback.loginSuccessful();
                                        }
                                    });
                                }
                            }
                        };
                        req.setUrl("https://www.googleapis.com/oauth2/v4/token");
                        req.addArgument("grant_type", "authorization_code");
                        // req.addArgument("client_id", "555462747934-iujpd5saj4pjpibo7c6r9tbjfef22rh1.apps.googleusercontent.com");
                        req.addArgument("client_id", clientId);
                        // req.addArgument("client_secret", "650YqplrnAI0KXb9LMUnVNnx");
                        req.addArgument("client_secret", clientSecret);
                        req.addArgument("redirect_uri", "");
                        req.addArgument("code", code);
                        req.addArgument("id_token", requestIdToken);
                        req.setPost(true);
                        req.setReadResponseForErrors(true);
                        NetworkManager.getInstance().addToQueue(req);
                    } else {
                        setAccessToken(new AccessToken(null, null));
                        Log.p("The access token was set to null because one of clientId, clientSecret, requestIdToken, or auth were null");
                        Log.p("The login succeeded, but you won't be able to make any requests to Google's REST apis using the login token.");
                        Log.p("In order to obtain a token that can be used with Google's REST APIs, you need to set the clientId, and clientSecret of" + "the GoogleConnect instance to valid OAuth2.0 Client IDs for Web Clients.");
                        Log.p("See https://console.developers.google.com/apis/credentials");
                        Log.p("You can get the OAuth2.0 client ID for this project in your google-services.json file in the oauth_client section");
                        Display.getInstance().callSerially(new Runnable() {

                            @Override
                            public void run() {
                                callback.loginSuccessful();
                            }
                        });
                    }
                } else {
                    if (callback != null) {
                        if (callback != null) {
                            Display.getInstance().callSerially(new Runnable() {

                                @Override
                                public void run() {
                                    callback.loginFailed(GooglePlayServicesUtil.getErrorString(result.getStatus().getStatusCode()));
                                }
                            });
                        }
                    }
                }
            }
        }
    });
}
Also used : Set(java.util.Set) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Intent(android.content.Intent) IOException(java.io.IOException) GoogleSignInResult(com.google.android.gms.auth.api.signin.GoogleSignInResult) ConnectionRequest(com.codename1.io.ConnectionRequest) GoogleSignInAccount(com.google.android.gms.auth.api.signin.GoogleSignInAccount) IntentResultListener(com.codename1.impl.android.IntentResultListener) AccessToken(com.codename1.io.AccessToken) JSONParser(com.codename1.io.JSONParser) Map(java.util.Map)

Example 2 with Oauth2

use of com.codename1.io.Oauth2 in project CodenameOne by codenameone.

the class GoogleConnect method createOauth2.

@Override
protected Oauth2 createOauth2() {
    Hashtable params = new Hashtable();
    params.put("approval_prompt", "force");
    params.put("access_type", "offline");
    Oauth2 auth = new Oauth2(oauth2URL, clientId, redirectURI, scope, tokenURL, clientSecret, params);
    return auth;
}
Also used : Hashtable(java.util.Hashtable) Oauth2(com.codename1.io.Oauth2)

Example 3 with Oauth2

use of com.codename1.io.Oauth2 in project CodenameOne by codenameone.

the class FaceBookAccess method createOAuth.

public Oauth2 createOAuth() {
    String scope = "";
    if (permissions != null && permissions.length > 0) {
        int plen = permissions.length;
        for (int i = 0; i < plen; i++) {
            String permission = permissions[i];
            scope += permission + ",";
        }
        scope = scope.substring(0, scope.length() - 1);
    }
    Hashtable additionalParams = new Hashtable();
    String p = Display.getInstance().getPlatformName();
    // on simulator BB and J2ME use the popup display (no need for javascript)
    if (Display.getInstance().getProperty("OS", "SE").equals("SE") || p.equals("rim") || p.equals("me")) {
        additionalParams.put("display", "popup");
    } else {
        additionalParams.put("display", "touch");
    }
    return new Oauth2("https://www.facebook.com/dialog/oauth", clientId, redirectURI, scope, "https://graph.facebook.com/oauth/access_token", clientSecret, additionalParams);
}
Also used : Hashtable(java.util.Hashtable) Oauth2(com.codename1.io.Oauth2)

Example 4 with Oauth2

use of com.codename1.io.Oauth2 in project CodenameOne by codenameone.

the class TwitterRESTService method initToken.

/**
 * Logs in to twitter as an application
 *
 * @param consumerKey the key to login with
 * @param consumerSecret the secret to to login with
 * @return the authorization token
 */
public static String initToken(String consumerKey, String consumerSecret) {
    ConnectionRequest auth = new ConnectionRequest() {

        protected void readResponse(InputStream input) throws IOException {
            JSONParser p = new JSONParser();
            Hashtable h = p.parse(new InputStreamReader(input));
            authToken = (String) h.get("access_token");
            if (authToken == null) {
                return;
            }
        }
    };
    auth.setPost(true);
    auth.setUrl("https://api.twitter.com/oauth2/token");
    // YOU MUST CHANGE THIS IF YOU BUILD YOUR OWN APP
    String encoded = Base64.encodeNoNewline((consumerKey + ":" + consumerSecret).getBytes());
    auth.addRequestHeader("Authorization", "Basic " + encoded);
    auth.setContentType("application/x-www-form-urlencoded;charset=UTF-8");
    auth.addArgument("grant_type", "client_credentials");
    NetworkManager.getInstance().addToQueueAndWait(auth);
    return authToken;
}
Also used : ConnectionRequest(com.codename1.io.ConnectionRequest) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Hashtable(java.util.Hashtable) JSONParser(com.codename1.io.JSONParser)

Example 5 with Oauth2

use of com.codename1.io.Oauth2 in project CodenameOne by codenameone.

the class Login method doLogin.

/**
 * Logs in the user.
 * If the service has a native login it will try to use that, otherwise an
 * Oauth2 web login will be used.
 */
public void doLogin() {
    if (isNativeLoginSupported()) {
        nativelogin();
    } else {
        if (oauth2URL == null) {
            System.out.println("No oauth2URL found Use setOauth2URL");
            return;
        }
        if (clientId == null) {
            System.out.println("No ClientId found Use setClientId");
            return;
        }
        if (redirectURI == null) {
            System.out.println("No redirectURI found Use setRedirectURI");
            return;
        }
        if (clientSecret == null) {
            System.out.println("No clientSecret found Use setClientSecret");
            return;
        }
        Oauth2 auth = createOauth2();
        auth.showAuthentication(new ActionListener() {

            public void actionPerformed(ActionEvent evt) {
                // success
                if (evt.getSource() instanceof AccessToken) {
                    AccessToken t = (AccessToken) evt.getSource();
                    setAccessToken(t);
                    if (callback != null) {
                        callback.loginSuccessful();
                    }
                    return;
                }
                if (evt.getSource() instanceof String) {
                    String t = (String) evt.getSource();
                    setAccessToken(new AccessToken(t, null));
                    if (callback != null) {
                        callback.loginSuccessful();
                    }
                    return;
                }
                if (evt.getSource() instanceof Exception) {
                    if (callback != null) {
                        Exception e = (Exception) evt.getSource();
                        Log.e(e);
                        callback.loginFailed(e.getMessage());
                    }
                }
            }
        });
    }
}
Also used : ActionListener(com.codename1.ui.events.ActionListener) ActionEvent(com.codename1.ui.events.ActionEvent) AccessToken(com.codename1.io.AccessToken) Oauth2(com.codename1.io.Oauth2) IOException(java.io.IOException)

Aggregations

Oauth2 (com.codename1.io.Oauth2)3 Hashtable (java.util.Hashtable)3 AccessToken (com.codename1.io.AccessToken)2 ConnectionRequest (com.codename1.io.ConnectionRequest)2 JSONParser (com.codename1.io.JSONParser)2 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 InputStreamReader (java.io.InputStreamReader)2 Intent (android.content.Intent)1 IntentResultListener (com.codename1.impl.android.IntentResultListener)1 ActionEvent (com.codename1.ui.events.ActionEvent)1 ActionListener (com.codename1.ui.events.ActionListener)1 GoogleSignInAccount (com.google.android.gms.auth.api.signin.GoogleSignInAccount)1 GoogleSignInResult (com.google.android.gms.auth.api.signin.GoogleSignInResult)1 Map (java.util.Map)1 Set (java.util.Set)1