mars requirement, rohini issue: oatuh token validatity for 1day,

 Based on your intention—to get a new token from the server every time and validate it, with the token being valid for at least 1 day—here’s how we can adjust the JavaScript and policy flow. This approach ensures a fresh token is fetched on each request and cached for 1 day (86400 seconds) to avoid unnecessary calls while maintaining validation.


### Updated Approach

- **Get Token Every Time**: Use the `ServiceCallout` to fetch a new token on each request, bypassing the cache initially.

- **Validate and Cache for 1 Day**: Store the token in the cache with a fixed 1-day expiration (86400 seconds) to ensure it’s reused for subsequent requests within that period.

- **Validation**: The token’s validity is implicitly handled by the OAuth server; if invalid, the `ServiceCallout` will fail, and you can add error handling.


### Updated JavaScript (`setCacheTimeout.js`)

This script will set the cache timeout to 1 day (86400 seconds) regardless of the `sapapim.expiresIn` value, ensuring the token is reused for 1 day before a new one is fetched.


```javascript

// Get pre-extracted variables

var accessToken = context.getVariable('sapapim.accessToken');

var expiresIn = context.getVariable('sapapim.expiresIn');

var tokenIssuedTime = context.getVariable('sapapim.tokenIssuedTime');


// Set cache timeout to 1 day (86400 seconds) as per requirement

var cacheTimeout = 86400; // 1 day in seconds

context.setVariable('cache.timeout', cacheTimeout);

print('cache.timeout set to: ' + cacheTimeout + ' seconds (1 day)');


// Update the Authorization header with the new token

if (accessToken) {

    context.setVariable('sapapim.Authorization', 'Bearer ' + accessToken);

    // Update tokenIssuedTime if not already set or if re-issued

    if (!tokenIssuedTime || isNaN(tokenIssuedTime)) {

        context.setVariable('sapapim.tokenIssuedTime', new Date().getTime() / 1000);

    }

} else {

    print('Warning: sapapim.accessToken is null, unable to set Authorization');

    context.setVariable('cache.timeout', 86400); // Fallback

}


// Optional: Log for debugging

print('sapapim.Authorization set to: ' + context.getVariable('sapapim.Authorization'));

print('sapapim.tokenIssuedTime: ' + context.getVariable('sapapim.tokenIssuedTime'));

```


### Updated Policy Flow

To ensure a new token is fetched every time and cached for 1 day:

1. **Remove or Disable `LookupCache`**:

   - Since you want a new token every time, avoid reusing the cached token initially. The `ServiceCallout` will always execute.


2. **Complete Policy Sequence**:

   ```xml

   <!-- ServiceCallout to get the token every time -->

   <ServiceCallout async="false" continueOnError="false" enabled="true" xmlns="http://www.sap.com/apimgmt">

       <Request clearPayload="true">

           <Set>

               <Headers>

                   <Header name="Authorization">{sapapim.Authorization}</Header>

               </Headers>

               <Verb>POST</Verb>

           </Set>

           <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>

       </Request>

       <Response>sapapim.tokenresponse</Response>

       <Timeout>30000</Timeout>

       <HTTPTargetConnection>

           <URL>https://effem-glb-ci-dev01-pr.authentication.us21.hana.ondemand.com/oauth/token?grant_type=client_credentials</URL>

       </HTTPTargetConnection>

   </ServiceCallout>


   <!-- Extract variables from the token response -->

   <ExtractVariables async="false" continueOnError="false" enabled="true" xmlns="http://www.sap.com/apimgmt">

       <JSONPayload>

           <Variable name="sapapim.accessToken" type="string">

               <JSONPath>$.access_token</JSONPath>

           </Variable>

           <Variable name="sapapim.expiresIn" type="integer">

               <JSONPath>$.expires_in</JSONPath>

           </Variable>

       </JSONPayload>

       <Source>sapapim.tokenresponse</Source>

       <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>

   </ExtractVariables>


   <!-- JavaScript to set cache timeout and update Authorization -->

   <Javascript async="false" continueOnError="false" enabled="true" xmlns="http://www.sap.com/apimgmt">

       <ResourceURL>jsc://setCacheTimeout.js</ResourceURL>

   </Javascript>


   <!-- PopulateCache to store the token for 1 day -->

   <PopulateCache async="false" continueOnError="false" enabled="true" xmlns="http://www.sap.com/apimgmt">

       <CacheKey>

           <KeyFragment>oauth_token</KeyFragment>

       </CacheKey>

       <Scope>Exclusive</Scope>

       <ExpirySettings>

           <TimeoutInSec>86400</TimeoutInSec> <!-- 1 day -->

       </ExpirySettings>

       <Source>sapapim.Authorization</Source>

   </PopulateCache>

   ```


### How It Works

1. **Token Fetch**:

   - The `ServiceCallout` executes on every request to get a new token from the server.


2. **Extraction**:

   - The `<ExtractVariables>` policy extracts `sapapim.accessToken` and `sapapim.expiresIn` from the response.


3. **Cache Configuration**:

   - The JavaScript sets `cache.timeout` to 86400 seconds (1 day), and the `PopulateCache` policy stores the `sapapim.Authorization` token with this expiration.

   - Subsequent requests within 1 day will use the cached token (if `LookupCache` is reintroduced), but since you want a new token every time, we’ll skip caching reuse for now.


4. **Validation**:

   - The token’s validity is managed by the OAuth server. If the token expires within the 1-day cache period (unlikely if the server issues tokens valid for at least 1 day), the next request will fail, and you can add error handling (e.g., `RaiseFault`).


### Adjusting for "New Token Every Time"

- If you strictly want a new token on every request and don’t want to cache it, remove the `<PopulateCache>` policy entirely. However, this will increase load on the OAuth server and may violate rate limits. To balance this:

  - Keep the `PopulateCache` but ensure the `ServiceCallout` always runs by not using `LookupCache` upfront.

  - The 1-day cache ensures the token is reused within that period, aligning with your "at least 1 day" validation requirement.


### Error Handling

Add a `RaiseFault` policy to handle token fetch failures:

```xml

<RaiseFault async="false" continueOnError="false" enabled="true" xmlns="http://www.sap.com/apimgmt">

    <FaultResponse>

        <Set>

            <Payload contentType="application/json">{"error": "Failed to retrieve OAuth token"}</Payload>

        </Set>

    </FaultResponse>

    <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>

</RaiseFault>

```


### Testing

- Deploy the flow and trigger a request to confirm a new token is fetched each time.

- Verify the cache timeout is set to 86400 seconds in the logs.

- Wait beyond 1 day to ensure the token refreshes without errors (though with `PopulateCache` removed, it will refresh on every request).


### Recommendation

- If your OAuth server issues tokens valid for at least 1 day, this setup works. If tokens expire sooner, reconsider using `LookupCache` to refresh only when the cache misses, adjusting the `TimeoutInSec` to match the token’s `expires_in` or a safe default (e.g., 7200 seconds).


Let me know if you need further refinements!

Popular posts from this blog

SAP CPI : camle expression in sap cpi , cm, router, filter and groovy script. format

pss book: గురు ప్రార్థనామంజరి . completed 21st july 2024

pss book : శ్రీకృష్ణుడు దేవుడా, భగవంతుడా completed , second review needed. 26th April 2024