How can we pass dynamic access token to every API request through authentication?

Not applicable

I am new to this apigee so I need your suggestions to make an API/webservice. Please help me on this. My requirement is that, I need to pass an access token value as header parameter to all my API requests.Prior to that I need to make an authentication call using some credentials (username,password,client id etc).As a result of this authentication call I will get an auth-token (this value is dynamic). I need to pass this auth-token value to all the upcoming API call as a header parameter.How can I achieve this using APIGEE.Please someone help me with some sample codes.Any help is appreciated.

Solved Solved
0 14 6,634
1 ACCEPTED SOLUTION

sidd-harth
Participant V

Hi @Geo V L, this can be achieved using Service Callout(SC), Extract Variable(EV) & Assign Message(AM) policies.

We can add them on the Proxyendpoint Preflow.

  1. First, we will be using an SC to call the authentication service(3rd party HTTP/s Service), you can hardcode, username, password, client id details here or get them dynamically from the request.
  2. If these values are coming from the request, then use an EV policy before SC to extract out these details & use them in SC.
  3. This SC will make a call to authentication service with the details & give you an auth-token in response.
  4. Use another EV to extract the required auth-token.
  5. Then use an AM policy to Set an Header with the extracted token from previous step.

I dont have sample code. Why don't you start working on a proxy by following above steps & then if you are stuck, post here.

View solution in original post

14 REPLIES 14

sidd-harth
Participant V

Hi @Geo V L, this can be achieved using Service Callout(SC), Extract Variable(EV) & Assign Message(AM) policies.

We can add them on the Proxyendpoint Preflow.

  1. First, we will be using an SC to call the authentication service(3rd party HTTP/s Service), you can hardcode, username, password, client id details here or get them dynamically from the request.
  2. If these values are coming from the request, then use an EV policy before SC to extract out these details & use them in SC.
  3. This SC will make a call to authentication service with the details & give you an auth-token in response.
  4. Use another EV to extract the required auth-token.
  5. Then use an AM policy to Set an Header with the extracted token from previous step.

I dont have sample code. Why don't you start working on a proxy by following above steps & then if you are stuck, post here.

Thank you so much.The first step is working fine for me and got the authToken as response.Following is my SC

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ServiceCallout async="false" continueOnError="false" enabled="true" name="authenticationCall" contentType="application/x-www-form-urlencoded">
    <DisplayName>authenticationCall</DisplayName>
    <Properties/>
    <Request clearPayload="true" variable="myRequest">
        <Set>
            <Headers>
                <Header name="Content-Type">application/x-www-form-urlencoded</Header>
            </Headers>
            <FormParams>
                <FormParam name="client_id">user123</FormParam>
                <FormParam name="client_secret">sample123</FormParam>
                <FormParam name="username">test@test.com</FormParam>
                <FormParam name="password">test</FormParam>
                <FormParam name="grant_type">password</FormParam>
            </FormParams>
            <Verb>POST</Verb>
            <Path/>
        </Set>
        <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>
    </Request>
    <Response>calloutResponse</Response>
    <HTTPTargetConnection>
        <Properties/>
        <URL>http://myUrl.com</URL>
    </HTTPTargetConnection>
</ServiceCallout>

How can I assign this response (Its a JSON object) to an EV and then to a header ??

Response is something like this

{
    "access_token": "XXXXXXXXX",
    "refresh_token": "YYYYYYY",
    "token_type": "bearer",
    "expires_in": 28800,
    "
}

The output of SC policy is saved to the Response tag. By default it is calloutResponse. So we can use this as a Source in EV policy.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ExtractVariables async="false" continueOnError="false" enabled="true" name="EV-Auth-Token">
    <DisplayName>EV-Auth-Token</DisplayName>
    <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
    <JSONPayload>
        <Variable name="auth_token">
            <JSONPath>$.access_token</JSONPath>
        </Variable>
    </JSONPayload>
    <Source clearPayload="false">calloutResponse</Source>
    <VariablePrefix>GEOvl</VariablePrefix>
</ExtractVariables>
<br>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AssignMessage async="false" continueOnError="false" enabled="true" name="AM-Set-Header">
    <DisplayName>AM-Set-Header</DisplayName>
    <Properties/>
    <Set>
        <Headers>
            <Header name="Authorization">{GEOvl.auth_token}</Header>
        </Headers>
    </Set>
    <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
    <AssignTo createNew="false" transport="http" type="request"/> 

</AssignMessage>

Do we need to assign this EV to any flow ?

Yes, we need to add them in a order, SC >> EV >> AS

Policies get executed only when attached to a flow.

Ok. I have added SC to the Proxyendpoint Preflow and AS to TargetEndPoint Preflow.Where I need to add EV ?

All 3 policies can be added on ProxyEndpoint Preflow.

Anyway, as you have added AS on Target Endpoint Preflow. Just add the EV before AS.

Hi,

My target end point is dynamic.I have go through this (https://community.apigee.com/questions/24408/how-can-i-dynamically-set-the-url-for-a-servicecal.html) reference,but it is not working for me.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ServiceCallout async="false" continueOnError="false" enabled="true" name="myServicePolicy">
<DisplayName>test</DisplayName>
<Properties/>
<Request clearPayload="true">
<Set>
<Headers>
<!--<Header name="Content-Type">application/json</Header>-->
<Header name="Authorization">Bearer {shareFiles.auth_token}</Header>
</Headers>
<Verb>GET</Verb>
<Path>{sc_urlPath}</Path>
</Set>
<IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>
</Request>
<Response>calloutResponseDownload</Response>
<HTTPTargetConnection>
<Properties/>
<URL>https://{hostName}{downloadUrl}</URL>
</HTTPTargetConnection>
</ServiceCallout>

In my Sc

 context.setVariable('hostName', hostName);
    context.setVariable('downloadUrl', downloadUrl);

I have Also tried the following method also

var siteUrl = 'https://' + hostName + downloadUrl;
context.setVariable("servicecallout.myServicePolicy.target.url", siteUrl);

Hi @Geo V L, please post this as a new question.

Also do you plan on using a single https protocol or both http and https protocols in SC policy?

Hello Sid, I'm following the same steps mentioned above but I'm getting 400 Bad Request. Whnee I used trace variable data is not showing. Is there any step missing from above requirement??

Hello Geo and Sid, I have the same requirements as well but my data is in the body. How can I set the data in body?

<Set>

..

<Body>

<Body name="preferred_username">username</Body>

<Body name="password">some_password</Body>

</Body>

</Set>

Is it the correct way to set the data from body because currently I'm doing this but it is giving me "steps.servicecallout.ExecutionFailed" error

No, actually there is no tag like body.

Please use Payload tags. Refer assign message policy document for more examples.

Thank you. It worked.

Code if someone needs:

<Set>

.....

<Payload contentType="application/json">

{"preferred_username":"username",

"password":"password"}

</Payload>

</Set>