Search code examples
javascriptspring-securitypostmanurlencode

Postman pre-request to get token doesn't work


At this time I can perform succesfully my Postman request to get my token. I'm using these parameters :

-Basic Authorization in the headers

-and this body -enter image description here

Now I would like to get this request as a pre-request script (and use an environment variable for the token).

Here is the script :

pm.sendRequest({
    url: 'http://localhost:8084/oauth/token',
    method: 'POST',
    header: {
        'Authorization':'Basic Y2xpZW50OnBhc3N3b3Jk',
        'content-type': 'application/x-www-form-urlencoded'
    },
    data:{
        'password':'secret',
        'username':'admin',
        'grant_type':'password'
    }
}, (err, res) => pm.environment.set("token", res.json().access_token));

It doesn't work with the response : Full authentication is required to access this resource.

What is wrong?

Thanks


Solution

  • You could change the data section to something like this?

    body:{
       mode:"urlencoded",
       urlencoded:[
          {
             key:"grant_type",
             value:"password"
          },
          {
             key:"username",
             value:"admin"
          },
          {
             key:"password",
             value:"secret"
          }
       ]
    }
    

    A great resource for pm.sendRequest() examples can be found here