New to api testing pre-request scripts - Automatically getting access token with OAuth 2.0 Grant Type 'Client Credentials' - api

I have been stuck for days on this and looked through many articles, but can not find a script that can help me.
The basis of the script is to automatically get authorization token, before i use a POST method.
As said before when getting a access token for this particular api the grant type is Client Crentials and the following fields are needed when manually getting the token :-
Token Name, Grant Type, Access Token URL, Client ID, Client Secrect, Scope and Client Authentication.
Is there a simple script that i can do this for me before actually doing the POST as it tiresome manually getting the token.
Thanks in advance with any help.
Kind Regards
Just an update i have found a way of actually getting the token now , so if you do the following.
Add a new request
Select 'Post'
Enter the api url
Click 'Body'
Click 'x-www-form-urlencoded'
I entered the following 'Keys'(enter your own corresponding 'values') - 'client_id', 'client_secret', 'scope' and 'grant type'
Click 'Send'
This will get you your token, i now need to find a way to either extract the token in a new request or find a way of putting this in the pre-request scripts, so I am able to enter the data need as 'raw' JSON.
Again if anyone can help, would appreciate it.
Kind Regards

Would this be any help to you? Or at least get you closer to what you need?
If you add this script to the Collection level pre-request script it will get the token and set this as the jwt variable. You can use this variable in the Headers for the main requests, using the {{jwt}} syntax - This script also gets the expiry_in value from the token response and sets this as a variable.
On each request in the collection, it will run the script and check to see if you have the AccessTokenExpiry and jwt properties in the environment file, it also checks to see if the token has expired. If any of those statements are true, it will get another token for you. If those are ok, it will use what you have set.
const moment = require('moment')
const getJWT = {
url: `<your token base path>/Auth/connect/token`,
method: 'POST',
header: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: {
mode: 'urlencoded',
urlencoded: [
{key: 'grant_type', value: 'client_credentials'},
{key: 'scope', value: '<scope details>'}
{key: 'client_id', value: 'your creds'}
{key: 'client_secret', value: 'your creds'}
]
}
}
var getToken = true
if (!_.has(pm.environment.toObject(), 'AccessTokenExpiry')
|| !_.has(pm.environment.toObject(), 'jwt')
|| pm.environment.get('AccessTokenExpiry') <= moment().valueOf()) {
} else {
getToken = false
}
if (getToken) {
pm.sendRequest(getJWT, (err, res) => {
if (err === null) {
pm.environment.set('jwt', `Bearer ${res.json().access_token}`)
var expiryDate = moment().add(res.json().expires_in, 's').valueOf()
pm.environment.set('AccessTokenExpiry', expiryDate)
}
})
}
To access the Collection level elements, if you hover over the collection name and click the ... icon, this will display a list of menu options. Select edit.

Related

Sync Token in Postman

A fresher to postman, currently working on API project where I need to delivery to the API and Token the client to integrate with them system, good is I successfully configure the Authorization as OAuth Type as Password Credentials and receiving perfect response as 200.
The issue/confusion is Token is getting expire every hour, I need to Get new Access Token every time.
So, the question is, is it anyway I can overcome this issue?
that no need to get new/refresh token.
can provide the one fix token to client.
You can do it like here. You can get the token in the pre-request field of the collection or request.
https://stackoverflow.com/a/73911458/10126763
EDIT
We can adapt it like this:
Take this and paste it in the "pre-request" field of the collection or the request you will use directly. Create an "environment" value named "accessToken". When each request is run, this method will run first and send the token value to the value in the environment.
// Set refresh and access tokens
const loginRequest = {
url: "exampleurl.com/etc/etc", //YOUR URL
method: 'GET',
header: {
'content-type': 'application/json',
'Accept': "*/*"
} //Since you will be using GET, I deleted the body. If you are sending value you can get the body field from the other example in the link.
};
pm.sendRequest(loginRequest, function (err, res) {
pm.environment.set("accessToken", res.json().accessToken); //The token returned in the response and the environment value to which the value will be sent
});

PassportJS OAuth2Strategy: authenticate returns 400 instead of redirecting

I'm trying to setup discord oauth2 pkce using passportjs and the passport-oauth2
const discordStrategy = new OAuth2Strategy({
authorizationURL: 'https://discord.com/api/oauth2/authorize',
tokenURL: 'https://discord.com/api/oauth2/token',
clientID: DISCORD_CLIENT_ID,
clientSecret: DISCORD_CLIENT_SECRET,
callbackURL: DISCORD_CALLBACK_URL,
state: true,
pkce: true,
scope: ['identity', 'scope'],
passReqToCallback: true,
},
(req: Request, accessToken: string, refreshToken: string, profile: DiscordUserProfile, cb: any) => {
prisma.user.findUnique({ where: { email: profile.email ?? '' }}).then(foundUser => {
if (foundUser === null) {
// Create a new user with oauth identity.
} else {
cb(null, foundUser)
}
}).catch(error => {
cb(error, null);
})
});
I've been following the google example as well as some others, these examples indicate that, I should be able to use:
passport.use('discord', discordStrategy);
and
authRouter.get('/discord', passport.authenticate('discord'));
and this should redirect to the OAuth2 providers login page, but instead, I get a 400 Bad Request "The request cannot be fulfilled due to bad syntax." The response body contains an object:
{"scope": ["0"]}
Why is this happening instead of the expected redirect?
My intention is that, once the user logs in, I should get a code, then I can post that code and the code verifier to get an access token, then once the access token is obtained, the actual authenticate call can be made
Edit: I put breakpoints in the passport.authenticate function and I stepped through it. It does actually get through everything and it calls the redirect. The parsed URL it generates, even if I copy it and manually navigate to the URL, it gives me the same, just gives:
{"scope": ["0"]}
and no login page, why?
If you add a version number to the base api url, e.g. /v9 it gives a full error message.
It turned out I had typo'd the scopes, I had 'identity' instead of 'identify' - now this part of the process is working as expected.

Strapi doesn't authorize JWT

Good morning,
I've encountered a weird issue with my strapi-project.
I have a standard user model which I query for info on the user's profile page via the /users/me endpoint. This was all working fine last week but as I tried logging in this morning, the authorization appeared to not work anymore. I log my user in via this code:
....
async submitForm() {
axios.post('http://localhost:1337/auth/local', {
'identifier': this.email,
'password': this.password
})
.then((response) => {
const { jwt, user } = response.data;
window.localStorage.setItem('jwt', jwt);
window.localStorage.setItem('userData', JSON.stringify(user));
router.push('/dashboard');
})
.catch((e) => {
this.$store.commit('LOGIN_ERROR', e)
});
},
...
Which then redirects to my dashboard which queries the /users/me endpoint like so:
let token = localStorage.jwt;
axios.get(`http://localhost:1337/users/me`, {
headers: {
Authorization: `Bearer ${token}`
}
})
.then((response) => {
console.log(response.data);
})
A few days ago this was working fine, also the token variable used in the post contais the token returned from the backend after logging in. Now strapi gives me an error in the console:
[2021-10-16T07:16:52.568Z] debug GET /users/me (5 ms) 500
[2021-10-16T07:17:03.231Z] debug POST /auth/local (76 ms) 200
[2021-10-16T07:17:24.915Z] error TypeError: Cannot read property 'type' of null
at module.exports (/home/user/WebstormProjects/strapi-project/node_modules/strapi-plugin-users-permissions/config/policies/permissions.js:35:14)
at async /home/user/WebstormProjects/strapi-project/node_modules/strapi-utils/lib/policy.js:68:5
at async serve (/home/user/WebstormProjects/strapi-project/node_modules/koa-static/index.js:59:5)
at async /home/user/WebstormProjects/strapi-project/node_modules/strapi/lib/middlewares/parser/index.js:48:23
at async /home/user/WebstormProjects/strapi-project/node_modules/strapi/lib/middlewares/xss/index.js:26:9
My first guess was that maybe something with axios was wrong e.g. that the token wasn't sent correctly in the request so I tried the same thing with webstorm's http client:
POST http://localhost:1337/auth/local
Content-Type: application/json
{
"identifier": "test#test.com",
"password": "..."
}
Which returns the user and token:
"jwt": "<TOKEN>",
If I try using this token to authenticate the user, however a get a 401
GET http://localhost:1337/users/me
Authorization: "Bearer <token>"
Accept: application/json
returns
{
"statusCode": 401,
"error": "Unauthorized",
"message": "Invalid token."
}
So I tried figuring out what was going on there and after an hour I noticed that when looking at the user in the backend the user didn't have the authenticated role assigned. When I changed this manually in the backend, the request authorization works again.
So can anyone maybe tell me what is going on here? Because from my understanding, when POSTing valid credentials to /auth/local the user's role should change to Authenticated, which was working some days back.
Is there something I'm missing?
Any help would be greatly appreciated,
greetings, derelektrischemoench
Okay, so let me reply to your first part:
"Because from my understanding, when POSTing valid credentials to /auth/local the user's role should change to Authenticated"
Answer is, not really. When you send valid credentials to the auth/local, Strapi just checks the database for matching username/email and password. If a user is found, then it fetches the role assigned that user and puts all the data in ctx.state.user.role. So you could have many other roles, like Viewer, Commenter etc with each having different set of access limits.
The different roles can be created here:
http://localhost:1337/admin/settings/users-permissions/roles
So depending on the roles assigned, Strapi will just fetch and store the values in ctx.state.user.role on each request via the strapi-plugin-users-permissions plugin for your convenience, so that you can easily check which user it is and which role it has in any controller or service file using the ctx from the request to provide any additional functionality.
You can check how it does it in the following file:
node_modules/strapi-plugin-users-permissions/config/policies/permissions.js
Now coming to what could have caused it:
Well it could have been you yourself. Possibly while saving the user or viewing user details you could have removed the role from the user and saved the record.
The other possibility could be a database switch.
It can also be a Strapi version upgrade that caused, but it's highly unlikely.
You could have a update query in the your code that updates the user model, where you might have missed the role parameter. So check your code once.
Nevertheless, it can simply be solved by re-assigning the user roles via the users module.

Unable to get access Token linkedin Oauth

I know some will put comment like this post is duplicate of so many questions, but I've tried many ways to achieve Access Token in linkedin Oauth. Explaining what i tried.
1) I'm following it's official doc's Linkedin Oauth2
2) I'm successfully getting Authorization code from step 2 and passing that code to step 3 for exchanging Auth code for getting Access Token. But i'm getting following error
{"error_description":"missing required parameters, includes an invalid parameter value, parameter more than once. : Unable to retrieve access token : appId or redirect uri does not match authorization code or authorization code expired","error":"invalid_request"}
3) According to some links i need to set content-type in the header.Link which tells to set content-type is missing
4)Then i tried calling https://www.linkedin.com/uas/oauth2/accessToken this service instead of POSt to GET. And passing data as queryParams.
5) Some link says oauth code expires in 20 sec, So i've checked, i'm making call for access token in less that 1 sec.
6) And if i pass data in Body params like as below and used url as https://www.linkedin.com/uas/oauth2/accessToken
var postData = {
grant_type: "authorization_code",
code: authCode,
redirect_uri: 'https%3A%2F%2Foauthtest-mydeployed-app-url',
client_id: 'my_client_id',
client_secret: 'secret_key'
};
7) With Get call my url i tried
https://www.linkedin.com/uas/oauth2/accessToken?grant_type=authorization_code&code='+authCode+'&redirect_uri=https%3A%2F%2Foauthtest-mydeployed-app-url&client_id=my_client_id&client_secret=secret_key
Still i'm getting Error even though status code is 200, i'm getting that error(with GET api)
and If POSt by passing postData in body i'm getting bad request 400 status code
Not understanding why m I not getting access code. I've read many solutions.
Sharing code as requested.
sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/m/MessageToast"
], function (Controller, MessageToast) {
"use strict";
return Controller.extend("OauthTest.OauthTest.controller.View1", {
onPress: function (evt) {
var sPath =
'https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=my_client_id&redirect_uri=https%3A%2F%2Foauthtest-mydeployed-app-url&state=DCEeFWf45A53sdfKef424&scope=r_basicprofile';
window.location.href = sPath;
var oRouter = new sap.ui.core.UIComponent.getRouterFor(this);
oRouter.navTo("View2", {
"username": "Test"
});
MessageToast.show(evt.getSource().getId() + " Pressed");
},
//after user allows access, user will be redirected to this app with code and state in URL
//i'm fetching code from URL in below method(call is happening in max.569ms)
onAfterRendering: function () {
var currentUrl = window.location.href;
var url = new URL(currentUrl);
var authCode = url.searchParams.get("code");
if (authCode !== undefined && authCode !== null) {
var postData = {
grant_type: "authorization_code",
code: authCode,
redirect_uri: 'https%3A%2F%2Foauthtest-mydeployed-app-url',
client_id: 'my_client_id',
client_secret: 'secret_key'
};
/* var accessTokenUrl = 'https://www.linkedin.com/uas/oauth2/accessToken?grant_type=authorization_code&code=' + authCode +'&redirect_uri=https%3A%2F%2Foauthtest-mydeployed-app-url&client_id=my_client_id&client_secret=secret_key';*/
var accessTokenUrl = 'https://www.linkedin.com/uas/oauth2/accessToken';
$.ajax({
url: accessTokenUrl,
type: "POST",
beforeSend: function (xhr) {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
},
data: postData,
success: function (data, textStatus, jqXHR) {
console.log(data);
alert('success');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
alert('error');
}
});
}
}
});
});
Help will be appriciated..!!!
Finally I am happy to post my answer after so much search.
Every step I did is correct only, but one thing I was missing here like, Linkedin API doesn't supports CORS.
I tried implementing Javascript SDK, that works like charm. But API wasn't.
Then I found very helpful Link which says I need to implement Rest API from backend by allowing CORS, not from front end.
Make sure to follow all the points which I mentioned above in my post.
And for Allow CORS follow this link. You will get data but only basic profile of user according to LinkedIn Terms data can be accessible
Hope this post may help someones time to search more

Using the Rally API to pull user profile

I am trying to use the Rally web service API to get some data. Code as blow. On IE it will pop out a login window, after entry login name and password, I am about to get some data. But when I use chrome, it response 401, not sure what I missing. I know there is SDK available, but due to some limitation, not able to use it. Any suggestions please?
var url = https://rally1.rallydev.com/slm/webservice/v2.0/users;
$.ajax({
url: url,
type: 'GET',
heards: { zsessionid: apiKey },
success: function(json) {
console.log(JSON.stringify(json));
}
},
error: function( req, status, err ) { console.log( 'something went wrong', status, err );
}
});
I'd love to know more about why you can't use the SDK. Anyway, in this case your config likely needs headers instead of heards to pass the api key.