Maximo Open Forum

 View Only

Fail to retrieve token from external system using Automation Script with OAuth2

  • 1.  Fail to retrieve token from external system using Automation Script with OAuth2

    Posted 12-11-2023 19:59

    Hello,

    I was trying to retrieve a token from an external system using an Automation Script with Action Launch Point, but all I'm getting is 400 bad request.

    Below is the code in jython that I was using. Maximo is 7.6.1.3.

    Could you please help me understand what I was doing wrong?

    Using the same data I'm able to retrieve the token using Postman.

    from org.apache.http import HttpEntity, HttpResponse, HttpStatus, NameValuePair
    from org.apache.http.client import HttpClient, methods
    from org.apache.http.client.entity import UrlEncodedFormEntity
    from org.apache.http.client.methods import HttpPost
    from org.apache.http.impl.client import HttpClientBuilder
    from org.apache.http.message import BasicNameValuePair
    from org.apache.commons.codec.binary import Base64
    from java.util import ArrayList
    from java.lang import String
    
    # client_id, client_secret, and scope obtained during OAuth2 registration
    client_id = 'my-client-id'
    client_secret = 'my-client-secret'
    scope = 'my-scope'
    
    # OAuth2 Token Endpoint
    token_url = 'my-token-url'
    
    # Create a base64 encoded string for client_id and client_secret
    client_credentials = client_id + ":" + client_secret
    encoded_credentials = String(Base64.encodeBase64(String.getBytes(client_credentials, 'ISO-8859-1')), "UTF-8")
    
    # Payload for requesting OAuth2 token
    data = ArrayList()
    data.add(BasicNameValuePair("grant_type", "client_credentials"))
    data.add(BasicNameValuePair("scope", scope))
    
    try:
        post = HttpPost(token_url)
        post.setHeader("Authorization", "Basic " + encoded_credentials)
        post.setHeader("Content-Type", "application/x-www-form-urlencoded")
        post.setEntity(UrlEncodedFormEntity(data))
    
        client = HttpClientBuilder.create().build()
        response = client.execute(post)
        
        if response.getStatusLine().getStatusCode() == HttpStatus.SC_OK:
            entity = response.getEntity()
            if entity is not None:
                content = entity.getContent()
                # Parse the JSON response to get the access token
                access_token = content.read()
                print("Access Token:", access_token)
        else:
            print("Failed to retrieve token:", response.getStatusLine().getStatusCode())
    
    except Exception as e:
        print("Error:", e)

    Thank you!


    #EverythingMaximo
    #Integrations

    ------------------------------
    Dragos Chitu
    EL
    ------------------------------