Search in sources :

Example 6 with BasicAuthentication

use of com.google.api.client.http.BasicAuthentication in project google-oauth-java-client by googleapis.

the class AuthorizationCodeFlowTest method subsetTestNewAuthorizationUrl.

public void subsetTestNewAuthorizationUrl(Collection<String> scopes) {
    AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(BearerToken.queryParameterAccessMethod(), new AccessTokenTransport(), new GsonFactory(), TOKEN_SERVER_URL, new BasicAuthentication(CLIENT_ID, CLIENT_SECRET), CLIENT_ID, "https://example.com").setScopes(scopes).build();
    AuthorizationCodeRequestUrl url = flow.newAuthorizationUrl();
    if (scopes.isEmpty()) {
        assertNull(url.getScopes());
    } else {
        assertEquals(Joiner.on(' ').join(scopes), url.getScopes());
    }
}
Also used : GsonFactory(com.google.api.client.json.gson.GsonFactory) BasicAuthentication(com.google.api.client.http.BasicAuthentication)

Example 7 with BasicAuthentication

use of com.google.api.client.http.BasicAuthentication in project google-oauth-java-client by googleapis.

the class AuthorizationCodeFlowTest method testCredentialCreatedListener.

public void testCredentialCreatedListener() throws IOException {
    MyCredentialCreatedListener listener = new MyCredentialCreatedListener();
    AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(BearerToken.queryParameterAccessMethod(), new AccessTokenTransport(), new GsonFactory(), TOKEN_SERVER_URL, new BasicAuthentication(CLIENT_ID, CLIENT_SECRET), CLIENT_ID, "authorizationServerEncodedUrl").setCredentialCreatedListener(listener).build();
    assertFalse(listener.called);
    flow.createAndStoreCredential(new TokenResponse(), "userId");
    assertTrue(listener.called);
}
Also used : GsonFactory(com.google.api.client.json.gson.GsonFactory) BasicAuthentication(com.google.api.client.http.BasicAuthentication)

Example 8 with BasicAuthentication

use of com.google.api.client.http.BasicAuthentication in project COSMIC-CryoEM-Gateway by cianfrocco-lab.

the class AuthCallbackAction method globuslogin.

public String globuslogin() throws Exception {
    // Handles the interaction with Globus Auth and does oauth flow
    // checks for errors, if so redirects back to home
    Enumeration<String> paramNames = request.getParameterNames();
    if (paramNames != null) {
        while (paramNames.hasMoreElements()) {
            if (paramNames.nextElement().contains(OauthConstants.ERROR)) {
                logger.error("You could not be logged into the portal: " + request.getParameter(OauthConstants.ERROR));
                // response.sendRedirect("");
                return "failure";
            }
        }
    }
    // Set up our Globus Auth/OAuth2 state
    config = OauthUtils.getConfig(OauthConstants.OAUTH_PORPS);
    String scopeString = config.getProperty(OauthConstants.SCOPES);
    List<String> scopes = Arrays.asList(scopeString.split(","));
    String auth_uri = config.getProperty(OauthConstants.AUTH_URI);
    GenericUrl token_server_url = new GenericUrl(config.getProperty(OauthConstants.TOKEN_SERVER_URL));
    String client_id = config.getProperty(OauthConstants.CLIENT_ID);
    String client_secret = config.getProperty(OauthConstants.CLIENT_SECRET);
    String dataset_endpoint_id = config.getProperty(OauthConstants.DATASET_ENDPOINT_ID);
    String dataset_endpoint_base = config.getProperty(OauthConstants.DATASET_ENDPOINT_BASE);
    String dataset_endpoint_name = config.getProperty(OauthConstants.DATASET_ENDPOINT_NAME);
    String endpoint_activation_uri = config.getProperty(OauthConstants.ENDPOINT_ACTIVATION_URI);
    // creates builder for flow object, necessary for oauth flow
    AuthorizationCodeFlow.Builder flowBuilder = new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(), new NetHttpTransport(), jsonFactory, token_server_url, new BasicAuthentication(client_id, client_secret), client_id, auth_uri).setScopes(scopes);
    // checks if user logged in or signed up, if signed up then adds "?signup=1" to the url
    if (Boolean.valueOf(request.getParameter(OauthConstants.SIGNUP))) {
        flowBuilder.setAuthorizationServerEncodedUrl(flowBuilder.getAuthorizationServerEncodedUrl() + OauthConstants.SIGNUP_PARAM);
    }
    // Create the flow object which mediates the Oauth flow steps
    AuthorizationCodeFlow flow = flowBuilder.build();
    String redirect_uri = config.getProperty(OauthConstants.REDIRECT_URI);
    // If there's no 'code' query string parameter, we're in this route starting a Globus Auth login
    // flow
    paramNames = request.getParameterNames();
    boolean codename_check = false;
    if (paramNames != null) {
        while (paramNames.hasMoreElements()) {
            if (paramNames.nextElement().contains(OauthConstants.CODE)) {
                codename_check = true;
                break;
            }
        }
    }
    if (!codename_check) {
        // String state = UUID.randomUUID().toString();
        String state = new BigInteger(130, new SecureRandom()).toString(32);
        // This is building the step 1: requesting a code
        authurl = flow.newAuthorizationUrl().setState(state).setRedirectUri(redirect_uri).build();
        // Remembers the random UUID to ensure that the same login flow continues once
        // redirected back to the client
        getSession().put(OauthConstants.OAUTH2_STATE, state);
        // response.sendRedirect(url);
        reportUserMessage("Redirect auth url: " + authurl);
        return "authredirect";
    } else {
        // If we do have a "code" param, we're coming back from Globus Auth
        // and can start the process of exchanging an auth code for a token.
        String passed_state = request.getParameter(OauthConstants.STATE);
        // client
        if (!passed_state.isEmpty() && passed_state.equals(getSession().get(OauthConstants.OAUTH2_STATE))) {
            String code = request.getParameter(OauthConstants.CODE);
            TokenResponse tokenResponse = null;
            Boolean isErrorFree = true;
            try {
                // This is step 2: exchanging the code for an Auth Token
                tokenResponse = flow.newTokenRequest(code).setRedirectUri(redirect_uri).execute();
            } catch (IOException e) {
                isErrorFree = false;
                logger.error("Caught: " + e);
                logger.error("Details: " + ((TokenResponseException) e).getDetails());
            }
            boolean redirect_flag = true;
            if (isErrorFree) {
                getSession().remove(OauthConstants.OAUTH2_STATE);
                // Parsing about the user
                logger.info("Token: " + tokenResponse.toPrettyString());
                IdToken id_token = IdToken.parse(jsonFactory, (String) tokenResponse.get(OauthConstants.ID_TOKEN));
                logger.info("Id token: " + id_token.toString());
                logger.info("Other tokens: " + tokenResponse.get("other_tokens"));
                ArrayList<ArrayMap> otokens = (ArrayList<ArrayMap>) tokenResponse.get("other_tokens");
                // for (ArrayMap js: jp) {
                // for (Object k: js.keySet())
                // logger.info("JS key: "+(String)k+" value: "+ js.get(k));
                // }
                String name = (String) id_token.getPayload().get(OauthConstants.NAME);
                String[] names = name.split(" ");
                String username = (String) id_token.getPayload().get(OauthConstants.PREFERRED_USERNAME);
                String email = (String) id_token.getPayload().get(OauthConstants.EMAIL);
                String identity = (String) id_token.getPayload().get(OauthConstants.SUB);
                String linkusername = null;
                // Step 3: Create the Credential object, which stores the Auth Token
                // Credential credentials = flow.createAndStoreCredential(tokenResponse, name);
                // logger.info("Credential: " + credentials.refreshToken());
                // logger.info("Credential: "+credentials.getJsonFactory().toPrettyString("other_tokens"));
                // String accesstoken = credentials.getAccessToken();
                String accesstoken = (String) ((ArrayMap) otokens.get(0)).get("access_token");
                // Stores the Credential and information about user as well as flags that the user has
                // been authenticated/logged in
                // getSession().put(OauthConstants.CREDENTIALS, credentials);
                /*
                    //create user directory on XSEDE repository
                    TransferAction txaction = new TransferAction(accesstoken,username);
                    logger.info("XSEDE Endpoint status......");
                    if (!txaction.endpointStatus(dataset_endpoint_id)) {
                        logger.info("XSEDE Endpoint activation....");
                        if (!txaction.delegateProxyActivation(dataset_endpoint_id)) {
                            logger.error("Unable to auto activate XSEDE endpoint, exiting");
                            return "failure";
                        }
                    }
                    txaction.createUserDir(dataset_endpoint_id, dataset_endpoint_base + username);
                    */
                OauthProfile db_profile = profileManager.load(identity);
                if (db_profile == null) {
                    // profile.setUserId(00001L);
                    profile.setUsername(username);
                    profile.setLinkUsername(username);
                    profile.setIdentityId(identity);
                    profile.setFirstName(names[0]);
                    profile.setLastName(names[1]);
                    profile.setEmail(email);
                    profile.setInstitution("");
                    // profile = profileManager.add(profile);
                    long userid = registerUser();
                    if (userid == -1L)
                        return "failure";
                    profile.setUserId(userid);
                    profileManager.addUser(profile);
                    getSession().put("user_id", userid);
                    getSession().put(OauthConstants.EMAIL, email);
                    getSession().put(OauthConstants.FIRST_NAME, names[0]);
                    getSession().put(OauthConstants.LAST_NAME, names[1]);
                    getSession().put(OauthConstants.INSTITUTION, "");
                } else {
                    // transfer
                    redirect_flag = false;
                    profile.setEmail(db_profile.getEmail());
                    profile.setIdentityId(db_profile.getIdentityId());
                    if (!activateLogin(null, db_profile.getLinkUsername()))
                        return "failure";
                    getSession().put("user_id", db_profile.getUserId());
                    getSession().put(OauthConstants.EMAIL, db_profile.getEmail());
                    getSession().put(OauthConstants.FIRST_NAME, db_profile.getFirstName());
                    getSession().put(OauthConstants.LAST_NAME, db_profile.getLastName());
                    getSession().put(OauthConstants.INSTITUTION, db_profile.getInstitution());
                    // update transfer record
                    List<String> tr = profileManager.loadRecord(db_profile.getUserId());
                    if (tr != null && tr.size() > 0) {
                        TransferAction txaction = new TransferAction(accesstoken, username);
                        for (String taskid : tr) profileManager.updateRecord(txaction.updateTask(taskid, null));
                    }
                // return "transfer";
                }
                linkusername = profile.getLinkUsername();
                getSession().put(OauthConstants.CREDENTIALS, accesstoken);
                getSession().put(OauthConstants.ID_TOKEN, id_token);
                getSession().put(OauthConstants.IS_AUTHENTICATED, true);
                getSession().put(OauthConstants.PRIMARY_USERNAME, username);
                // getSession().put("link_username", linkusername);
                getSession().put(OauthConstants.PRIMARY_IDENTITY, identity);
                getSession().put(OauthConstants.ENDPOINT_ACTIVATION_URI, endpoint_activation_uri);
                // initial setup for source and destination endpoint
                getSession().put(OauthConstants.DATASET_ENDPOINT_ID, dataset_endpoint_id);
                getSession().put(OauthConstants.DATASET_ENDPOINT_BASE, dataset_endpoint_base + linkusername + "/");
                getSession().put(OauthConstants.DATASET_ENDPOINT_NAME, dataset_endpoint_name);
                getSession().put(OauthConstants.DEST_BOOKMARK_ID, "XSERVER");
                getSession().put(OauthConstants.DEST_ENDPOINT_ID, dataset_endpoint_id);
                getSession().put(OauthConstants.DEST_ENDPOINT_PATH, dataset_endpoint_base + linkusername + "/");
                getSession().put(OauthConstants.DEST_ENDPOINT_NAME, dataset_endpoint_name);
                getSession().put(OauthConstants.DEST_DISP_NAME, dataset_endpoint_name);
                // in case, the source is Comet
                /*
                    getSession().put(OauthConstants.SRC_BOOKMARK_ID,"XSERVER");
                    getSession().put(OauthConstants.SRC_ENDPOINT_ID,dataset_endpoint_id);
                    getSession().put(OauthConstants.SRC_ENDPOINT_PATH,dataset_endpoint_base+linkusername+"/");
                    getSession().put(OauthConstants.SRC_ENDPOINT_NAME,dataset_endpoint_name);
                    getSession().put(OauthConstants.SRC_DISP_NAME,dataset_endpoint_name);
                    */
                EndpointListAction iplistaction = new EndpointListAction(accesstoken, username);
                // iplistaction.my_endpoint_list();
                // List<Map<String,Object>> bookmarklist = iplistaction.getBookmarklist();
                List<Map<String, Object>> bookmarklist = iplistaction.my_bookmark_list();
                if (bookmarklist != null && bookmarklist.size() > 0) {
                    boolean flag = false;
                    for (int i = 0; i < bookmarklist.size(); i++) {
                        Map<String, Object> bmmap = bookmarklist.get(i);
                        String bname = (String) bmmap.get("name");
                        String[] bnamea = bname.split("::");
                        if (bnamea.length == 2) {
                            flag = true;
                            if (bnamea[1].equals("SOURCE")) {
                                // in case the source is Comet
                                /*
                                    getSession().put(OauthConstants.SRC_BOOKMARK_ID, (String) bmmap.get("id"));
                                    getSession().put(OauthConstants.SRC_ENDPOINT_ID, (String) bmmap.get("endpoint_id"));
                                    getSession().put(OauthConstants.SRC_ENDPOINT_NAME, bname);
                                    getSession().put(OauthConstants.SRC_DISP_NAME, bname.split("::")[0]);
                                    getSession().put(OauthConstants.SRC_ENDPOINT_PATH, (String) bmmap.get("path"));

                                    getSession().put(OauthConstants.DEST_BOOKMARK_ID, "XSERVER");
                                    getSession().put(OauthConstants.DEST_ENDPOINT_ID, dataset_endpoint_id);
                                    getSession().put(OauthConstants.DEST_ENDPOINT_NAME, dataset_endpoint_name);
                                    getSession().put(OauthConstants.DEST_DISP_NAME, dataset_endpoint_name);
                                    getSession().put(OauthConstants.DEST_ENDPOINT_PATH, dataset_endpoint_base + linkusername + "/");
                                    */
                                getSession().put(OauthConstants.SRC_BOOKMARK_ID, (String) bmmap.get("id"));
                                getSession().put(OauthConstants.SRC_ENDPOINT_ID, (String) bmmap.get("endpoint_id"));
                                getSession().put(OauthConstants.SRC_ENDPOINT_NAME, bname);
                                getSession().put(OauthConstants.SRC_DISP_NAME, bname.split("::")[0]);
                                getSession().put(OauthConstants.SRC_ENDPOINT_PATH, (String) bmmap.get("path"));
                            } else {
                                getSession().put(OauthConstants.SRC_BOOKMARK_ID, "XSERVER");
                                getSession().put(OauthConstants.SRC_ENDPOINT_ID, dataset_endpoint_id);
                                getSession().put(OauthConstants.SRC_ENDPOINT_NAME, dataset_endpoint_name);
                                getSession().put(OauthConstants.SRC_DISP_NAME, dataset_endpoint_name);
                                getSession().put(OauthConstants.SRC_ENDPOINT_PATH, dataset_endpoint_base + linkusername + "/");
                                getSession().put(OauthConstants.DEST_BOOKMARK_ID, (String) bmmap.get("id"));
                                getSession().put(OauthConstants.DEST_ENDPOINT_ID, (String) bmmap.get("endpoint_id"));
                                getSession().put(OauthConstants.DEST_ENDPOINT_PATH, (String) bmmap.get("path"));
                                getSession().put(OauthConstants.DEST_ENDPOINT_NAME, bname);
                                getSession().put(OauthConstants.DEST_DISP_NAME, bname.split("::")[0]);
                            // in case, the source is Comet
                            /*
                                    getSession().put(OauthConstants.DEST_BOOKMARK_ID, (String) bmmap.get("id"));
                                    getSession().put(OauthConstants.DEST_ENDPOINT_ID, (String) bmmap.get("endpoint_id"));
                                    getSession().put(OauthConstants.DEST_ENDPOINT_PATH, (String) bmmap.get("path"));
                                    getSession().put(OauthConstants.DEST_ENDPOINT_NAME, bname);
                                    getSession().put(OauthConstants.DEST_DISP_NAME, bname.split("::")[0]);
                                    */
                            }
                            break;
                        }
                    }
                    if (!flag) {
                        Map<String, Object> bmmap = bookmarklist.get(0);
                        String bm_id = (String) bmmap.get("id");
                        String bname = (String) bmmap.get("name");
                        // in case, the destination is Comet
                        /*
                            bname += "::DEST";
                            logger.info("update bookmark: "+bm_id);
                            iplistaction.updateBookmark(bm_id,bname);
                            getSession().put(OauthConstants.DEST_BOOKMARK_ID, bm_id);
                            getSession().put(OauthConstants.DEST_ENDPOINT_ID, (String) bmmap.get("endpoint_id"));
                            getSession().put(OauthConstants.DEST_ENDPOINT_NAME, bname);
                            getSession().put(OauthConstants.DEST_DISP_NAME, (String) bmmap.get("disp_name"));
                            getSession().put(OauthConstants.DEST_ENDPOINT_PATH, (String) bmmap.get("path"));
                            */
                        bname += "::SOURCE";
                        logger.info("update bookmark: " + bm_id);
                        iplistaction.updateBookmark(bm_id, bname);
                        getSession().put(OauthConstants.SRC_BOOKMARK_ID, bm_id);
                        getSession().put(OauthConstants.SRC_ENDPOINT_ID, (String) bmmap.get("endpoint_id"));
                        getSession().put(OauthConstants.SRC_ENDPOINT_NAME, bname);
                        getSession().put(OauthConstants.SRC_DISP_NAME, (String) bmmap.get("disp_name"));
                        getSession().put(OauthConstants.SRC_ENDPOINT_PATH, (String) bmmap.get("path"));
                    }
                } else {
                    // return "dataendpoints";
                    return "transfer";
                }
            }
            if (redirect_flag) {
                return "profileredirect";
            } else {
                return SUCCESS;
            }
        } else {
            OAuthSystemException oauth_ex = new OAuthSystemException("Mismatching Oauth States");
            reportError(oauth_ex, "Mismatching Oauth States");
            return "failure";
        // Something went wrong with state value matching
        // throw new OAuthSystemException("Mismatching Oauth States");
        }
    }
}
Also used : JsonString(com.google.api.client.json.JsonString) GenericUrl(com.google.api.client.http.GenericUrl) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) IdToken(com.google.api.client.auth.openidconnect.IdToken) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) SecureRandom(java.security.SecureRandom) ArrayMap(com.google.api.client.util.ArrayMap) IOException(java.io.IOException) BasicAuthentication(com.google.api.client.http.BasicAuthentication) BigInteger(java.math.BigInteger) OauthProfile(edu.sdsc.globusauth.model.OauthProfile) ArrayMap(com.google.api.client.util.ArrayMap)

Example 9 with BasicAuthentication

use of com.google.api.client.http.BasicAuthentication in project google-oauth-java-client by googleapis.

the class CredentialTest method testRefreshToken_refreshTokenErrorWith500.

public void testRefreshToken_refreshTokenErrorWith500() throws Exception {
    AccessTokenTransport transport = new AccessTokenTransport();
    transport.statusCode = 500;
    Credential access = new Credential.Builder(BearerToken.queryParameterAccessMethod()).setTransport(transport).setJsonFactory(JSON_FACTORY).setTokenServerUrl(TOKEN_SERVER_URL).setClientAuthentication(new BasicAuthentication(CLIENT_ID, CLIENT_SECRET)).build().setExpiresInSeconds(3600L).setAccessToken(ACCESS_TOKEN).setRefreshToken(REFRESH_TOKEN);
    assertFalse(access.refreshToken());
    assertNotNull(access.getAccessToken());
    assertEquals("refreshToken", access.getRefreshToken());
    assertNotNull(access.getExpirationTimeMilliseconds());
}
Also used : BasicAuthentication(com.google.api.client.http.BasicAuthentication)

Example 10 with BasicAuthentication

use of com.google.api.client.http.BasicAuthentication in project google-oauth-java-client by googleapis.

the class CredentialTest method testRefreshToken_refreshTokenErrorWith400.

public void testRefreshToken_refreshTokenErrorWith400() throws Exception {
    AccessTokenTransport transport = new AccessTokenTransport();
    transport.statusCode = 400;
    Credential access = new Credential.Builder(BearerToken.queryParameterAccessMethod()).setTransport(transport).setJsonFactory(JSON_FACTORY).setTokenServerUrl(TOKEN_SERVER_URL).setClientAuthentication(new BasicAuthentication(CLIENT_ID, CLIENT_SECRET)).build().setExpiresInSeconds(3600L).setAccessToken(ACCESS_TOKEN).setRefreshToken(REFRESH_TOKEN);
    try {
        access.refreshToken();
        fail("Expected " + TokenResponseException.class);
    } catch (TokenResponseException e) {
    // Expected
    }
    assertNull(access.getAccessToken());
    assertEquals("refreshToken", access.getRefreshToken());
    assertNull(access.getExpirationTimeMilliseconds());
}
Also used : BasicAuthentication(com.google.api.client.http.BasicAuthentication)

Aggregations

BasicAuthentication (com.google.api.client.http.BasicAuthentication)12 GsonFactory (com.google.api.client.json.gson.GsonFactory)5 GenericUrl (com.google.api.client.http.GenericUrl)4 IOException (java.io.IOException)3 UserAgentHttpRequestInitializer (ch.cyberduck.core.http.UserAgentHttpRequestInitializer)2 PasswordTokenRequest (com.google.api.client.auth.oauth2.PasswordTokenRequest)2 TokenResponse (com.google.api.client.auth.oauth2.TokenResponse)2 HttpRequest (com.google.api.client.http.HttpRequest)2 HttpRequestFactory (com.google.api.client.http.HttpRequestFactory)2 LowLevelHttpRequest (com.google.api.client.http.LowLevelHttpRequest)2 ApacheHttpTransport (com.google.api.client.http.apache.v2.ApacheHttpTransport)2 MockLowLevelHttpRequest (com.google.api.client.testing.http.MockLowLevelHttpRequest)2 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)2 DescriptiveUrl (ch.cyberduck.core.DescriptiveUrl)1 DisabledCertificateIdentityCallback (ch.cyberduck.core.DisabledCertificateIdentityCallback)1 DisabledCertificateTrustCallback (ch.cyberduck.core.DisabledCertificateTrustCallback)1 DisabledLoginCallback (ch.cyberduck.core.DisabledLoginCallback)1 DisabledTranscriptListener (ch.cyberduck.core.DisabledTranscriptListener)1 Host (ch.cyberduck.core.Host)1 DAVSSLProtocol (ch.cyberduck.core.dav.DAVSSLProtocol)1