When testing some api, the token need to be generated each 3min and I would like to do the refresh automatically, I did the following
I have a collection "CollectionGetter" which contain some requests
from "CollectionGetter" collection :
I've added the following script in "Tests" tab
var jsonData = pm.response.json();
pm.environment.set('getToken', jsonData.access_token);
on authorozation tab,set :
Type = Bearer token
Token {{getToken}}
then selected a request under CollectionGetter :
getAccount (GET url/api/account)
Auth = inherit autho from parent
and sent it
=> got a 401 JSONError: No data, empty input at 1:1
Any help ?
is my configuration correct
Related
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
});
I want to invoke an api that returns bearer token (GET method). I can fetch Bearer Token successfully using .Net code. But with ADF I get only 'OK' and I see no option to fetch the Bearer Token.
Example:
ApiUrl = "https://myapi.mysite.org/api/ApiToken?user=u111&password=p111"
if status code = 'OK' then deserialize result content to fetch toekn.
Sample .Net code I used to fetch Bearer Token successfully:
var result = client.PostAsync(ApiUrl).Result;
string strRes = result.StatusCode.ToString();
if (strRes == "OK")
{
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject(result.Content.ReadAsStringAsync().Result);
varToken = obj.Token;
}
Use POST method in Azure data factory web activity to get the access token from an API.
Add header as content-Type: application/x-www-form-urlencoded and pass the access credentials in the body part.
You can refer to this link1 & link2 for working examples.
I am having trouble in making authentication work using an external frontend ( vue ) with my symfony app. The main problem is the "Invalid CSRF token" error. I have a login form in vue which sends an object containing the username, password, and the csrf token ( which I get from symfony tokengenerator ). I have a custom authenticator where I create the user passport and add the token to it.
public function authenticate(Request $request): PassportInterface
{
$username = $request->request->get('username', '');
$request->getSession()->set(Security::LAST_USERNAME, $username);
$this->logger->info('The token is', [$request->get('_csrf_token')]);
$passport = new Passport(
new UserBadge($username),
new PasswordCredentials($request->request->get('password', '')),
);
$passport->addBadge(new CsrfTokenBadge('authenticate', $request->get('_csrf_token')));
return $passport;
}
It makes it through to the AuthenticationManager.php, where it enters the executeAuthenticator method. The error comes after the CheckPassportEvent is dispatched, from CSRFProtectionListener. It fails on the
if (false === $this->csrfTokenManager->isTokenValid($csrfToken)).
I have tried to get the tokenmanager instance inside of my authenticator and create the token there and add it to the passport.
$token = $this->csrfTokenManager->getToken('authenticate'); $passport->addBadge(new CsrfTokenBadge($token->getId(), $token->getValue()));
This lets me get past the authentication, but immediately afterwards, when it redirects to the next path, it gives me an error "Access denied, the user is not fully authenticated; redirecting to authentication entry point.". After some debugging, it seems that the token storage is empty ( the token is saved to the storage when the getToken() method is called ).
When I do the authentication with the twig template, it works flawlessly. How exactly {{ csrf_token('authenticate') }} makes and handles the token I do not understand. Any input would be appreciated.
You have to pass the Authenticationintention as a string. In your example its "authenticate".
$passport->addBadge(new CsrfTokenBadge(' ---> authenticate <--- ', $request->get('_csrf_token')));
To check it you should use a code like this:
if (false === $this->csrfTokenManager->isTokenValid(new CsrfToken('authenticate' $YOUR_TOKEN_HERE))
or from a controller:
$this->isCsrfTokenValid('authenticate', $YOUR_TOKEN_HERE)
enter code here
In Symfony 5 you should work with the CSRF Protection like this:
In Twig, you can generate a CSRF Token with the "csrf_token" method. This Method is described here https://symfony.com/doc/current/security/csrf.html#generating-and-checking-csrf-tokens-manually.
You can validate the token in a controller using the "isCsrfTokenValid" function which lives in the controller class which you are extending.
Check this for more information:
https://symfony.com/doc/4.4/security/csrf.html#generating-and-checking-csrf-tokens-manually
I think the problem is that youre using a new Symfony version but using old practicies.
This is the message I get when I am trying to get the token data using web.contents query from "VMware vRealize Automation API":
There was an error when processing the data in the dataset.
Please try again later or contact support. If you contact support, please provide these details.
Data source error
{"error":{"code":"ModelRefresh_ShortMessage_ProcessingError","pbi.error":{"code":"ModelRefresh_ShortMessage_ProcessingError","parameters":
{},"details":[{"code":"Message","detail":{"type":1,"value":"Web.Contents failed to get contents from 'https://xxxxxxxxx.com/identity/api/tokens'
(404): Not Found"}}],"exceptionCulprit":1}}}
Table: GetToken.
The url passed to the first parameter of Web.Contents (authUrl = "https://xxxxxxxxx.com/identity/api/tokens") is accessible but always return the HTTP ERROR 405, probably
because this API uses a a JSON object in the request body parameter with the users credentials to obtain the Response.
API
My query
The main issues:
Your API uses HTTP POST verses GET, so you need to set Options[Content]
You can get refresh errors on the service unless you use Options[RelativePath]
You can "opt-in" to handling errors for specific HTTP Status codes, combined with Value.MetaData you get more detailed error messages.
Let it generate JSON for you from records and lists by using Query or Content parameters see: docs: Web.Contents
This is equivalent to your curl POST request
let
BaseUrl = "https://www.example.com",
Options = [
RelativePath = "/identity/api/tokens",
Headers = [
Accept="application/json"
],
Content = [
username = "username",
password = "password",
tenant = "tenant"
],
ManualStatusHandling = {400, 405}
],
// wrap 'Response' in 'Binary.Buffer' if you are using it multiple times
response = Web.Contents(BaseUrl, Options),
buffered = Binary.Buffer(response),
response_metadata = Value.Metadata(response),
status_code = response_metadata[Response.Status],
from_json = Json.Document(final_result)
in
from_json
I have related Web.Contents examples here, like Chaining Web.Contents requests: ninmonkeys.com/Power-Query-Custom-Functions-Cheat-Sheet
I am trying to string a few Postman requests together for testing.
In the first request I set a global variable as a test script.
tests['Status code is 200'] = (responseCode.code === 200);
if (responseCode.code === 200) {
try {
let jwt = responseBody.replace(/"/g, '');
pm.globals.set("jwt", jwt);
console.log("Variable will be set to", jwt);
}
catch(e) {
console.log(e);
}
}
In the second request I run a pre-request script as
let jwt = pm.globals.get("jwt");
Then I try to pass it into the header
Is it possible to pass a value into the header when running tests in the runner?
When running tests in the Runner the second request fails due to having an invalid jwt, and the Postman docs only show examples passing variables into the URL.
It's covered in postman auth.
Authenticate to get the JWT(oken) - Token API request
Add the test in to capture the token
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("jwt", jsonData.token);
Authorization > Type > Bearer Token
Token: {{jwt}}
Setup your Environment
Select the Environment
Select Keep variable values from the Collection Runner dialog (if you are running it in command line)
Note: I'm using version 6.3.0.