Confluence Retirement

In an effort to consolidate USGS hosted Wikis, myUSGS’ Confluence service is scheduled for retirement on January 27th, 2023. The official USGS Wiki and collaboration space is now SharePoint. Please migrate existing spaces and content to the SharePoint platform and remove it from Confluence at your earliest convenience. If you need any additional information or have any concerns about this change, please contact myusgs@usgs.gov. Thank you for your prompt attention to this matter.
Child pages
  • Logging in and Obtaining a JOSSO_SESSIONID

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
package gov.usgs

@Grab(group='org.apache.httpcomponents', module='httpclient', version='4.2.1')
@Grab(group='org.apache.httpcomponents', module='httpmime', version='4.2.1')

import org.apache.http.client.*
import org.apache.http.impl.client.DefaultHttpClient
import org.apache.http.client.methods.*
import org.apache.http.util.EntityUtils

//ScienceBase URL
def baseUrl = "https://www.sciencebase.gov/catalog"
//ScienceBase beta URL
//def baseUrl = "https://beta.sciencebase.gov/catalog"

//Username and password, these should be a service account. Usernames must be all lowercase, check logging in to
//http://my.usgs.gov with the exact username and password if logging in fails.
def username = "sbdocumentationtesting"
def password = "k+I7]!iAIZ^4..."

//Login
String josso_sessionid = login(baseUrl, username, password)

//Check that we logged in correctly
if(!josso_sessionid) {println "fail"; System.exit(1)}
println josso_sessionid




/**
 * Login to ScienceBase and return a HttpClient
 *
 * @param baseUrl   Base URL to authenticate on, eg. https://my.usgs.gov/catalog
 * @param username  The plain text username to authenticate on, use your own or a service account
 * @param password  The plain text password to authenticate on
 * @return          The josso_sessionid from the cookie received when logging in
 */
String login(String baseUrl, String username, String password){
    def encodedUsername = URLEncoder.encode(username)
    def encodedPassword = URLEncoder.encode(password)

    //Create a client for sending files, they will share cookies through this
    HttpClient httpClientLogin = new DefaultHttpClient()
    //Login
    HttpGet httpGet = new HttpGet(("${baseUrl}/?josso_username=${encodedUsername}&josso_password=${encodedPassword}").toURI())
    httpGet.addHeader("Accept", "application/json")
    //login
    def loginResponse = httpClientLogin.execute(httpGet)
    //Must do this to complete the login and release httpClientLogin
    def loginString = EntityUtils.toString(loginResponse.getEntity())

    def josso_sessionid_cookie = httpClientLogin.getCookieStore().getCookies().find{it.name == "JOSSO_SESSIONID"}
    if(loginResponse.statusLine.toString().contains("200") && josso_sessionid_cookie){
        return josso_sessionid_cookie.value
    }
    else return null
}