Okta authorization fails

Prior to any action my script is required to authenticate via the UserId/Password credentials to get the valid authentication token. Authentication is based on a standard OAuth 2 grant type: Password Credentials. End User will need to use the credential’s and need to make a call to the OKTA URL to get the proper token. Bearer token that is to be returned by the OKTA authentication endpoint. The following CURL command works. (I also have a working postman and Jmeter script).

curl --location --request POST 'https://host.com/oauth2/<redacted>/v1/token' --header 'Authorization: Basic <redacted>=' --header 'Content-Type: application/x-www-form-urlencoded' --header 'Cookie: JSESSIONID=<redacted>' --data-urlencode 'grant_type=password' --data-urlencode 'username=<redacted>@gmail.com' --data-urlencode 'password=<redacted>@<redacted>' --data-urlencode 'scope=openid'.

The following K6 script fails with a http 400 bad request error and the authorisation fails. Is there something obvious i am doing wring in this script.

import http from 'k6/http'
import { check } from "k6";

export default function () {
    var url = 'https://host/oauth2/<redacted>/v1/token';

    var headerParam = {
        headers: {
            'Authorization': 'Basic <redacted>=',
            'Content-Type': 'application/x-www-form-urlencoded',
            'Cookie': 'JSESSIONID=<redacted>'
        }
    };

    //lets define body - accepts email and password 
    var payload = JSON.stringify({
        grant_type: 'password',
        username: '<redacted>@gmail.com',
        password: '<redacted>@<redacted>',
        scope: 'openid'
    });

    // URL, HEADER, JSON BODY
    let response = http.post(url, headerParam, payload)

    check(response, {
        success: r => r.status == 200
      });
    
}

hi @pbains1,

You have switched the order of the headers and the body in the http.post call - it is “url, body, params”

Hi mystoykov,

I have switched the order as you quite rightly observed they were the wrong way around. However i now get another error (after switching debugging to full) which i dont understand. As you can see i have specified the grant_type in the header as grant_type: ‘password’ but the error seems to suggest that it is not specified.

{“error”:“invalid_request”,“error_description”:“The token request must specify a ‘grant_type’. Valid values: [password, authorization_code]”}

You are also sending a json body in k6 but a urlencoded one with curl.

Does it work if you just don’t call JSON.stringify on the object before you send it?

Hi,

I removed the JSON.stringify and the request works now. Thanks a lot.

Parm