How can we handle Callback URL redirection in FD serverless app?

Hi Team,

Please help with the queries posted below:
We were able to call the API with $request.
As per our requirement, after calling 1st api with JSON request, we are supposed to do the following in the same serverless app (server.js file) only:

  1. Make a call to a 2nd API URL with GET request. (This we will be achieve with the documentation) .
  2. Now the 2nd API (mentioned in point 1), does not return JSON response. It does a URL redirection to our application(we can let them know to which URL to redirect) and appends a “AUTHORIZATION CODE”, in the url like this: ?code=&scope=

So our Main Requirement is to get the Authorize Code from the callback URL.This has to be done in server.js only which is invoked on TicketCreation.

Can you please suggest how we can achieve this? Would be really helpful if you could provide a sample like before.

In continuation of the above question, if we are to provide a redirection URL of our app to the API which we are calling, what would be the URL of our serverless app? It is understood that it is server.js is invoked during onTicketCreation, so does this type of app have any URL of its own, which we can use for this redirection purpose and read the TOKEN from text appended to the URL?

Are you using the Platform’s OAuth feature?

Below are the redirect URLs that you might be looking for.

For this question to be answered,

I might need some more context about the usecase that you are trying to solve. Can you please share the problem that you are trying to solve? To see if I can get more help to understand the following question as well.

We are creating a FD serverless app, which is invoked onTicketCreation. From this APP, we need to call an API-which does a callback/redirect to a URL which has to be specified by us and gives a AuthorizationCode in the URL like this-http://example.com?code=<>&scope=.

Our serverless app needs to fetch this code from this callback. So, are question is, what URL can we give here, such that it will be accessible to our serverless app?
This won’t be accessible to our serverless app right, correct- Testing : http://localhost:10001/auth/callback?

Secondly, even after providing the URL, our requirement is not to get the HTML in response, rather just pick the authorization code from the URL of the page. Any way we can do that?

Is your goal here is to perform OAuth by following the above mentioned process? Or is it not related to Authentication at all. Please clarify.

cc: @rohan15

Hi Saif/Team,

We our ultimate aim is to do the following (Document reference pasted below) in the serverless app:

For Authorization Code Generation For the authorization code grant type flow, you need to obtain an authorization code before you can request an access token. This is responsible for redirecting the user to a login page/app (which is a pre-registered callback URL), where the end user can safely authenticate and authorize the client app to access their protected resources without divulging their username and password to the client app.
Sample Request:
https://prod.com.mm/oauth/v1/userAuthorize?client_id={consumer_key}&response_type =code&scope=READ

Callback URL Redirection Response:
Partner Callback URL?code=Authorize Code&scope=

Seems like you are trying to reproduce the OAuth flow.

Maybe you haven’t tried, we provide this process as part of Platform’s feature - Please see this page.

As a developer building an sdk app,

  1. You need to create a oauth_config.json file in tha app’s config/ folder.
  2. All details that the 3rd party needs to Authorize your app, such as Client ID, Secret, scope , authorize and token end points can be mentioned in this file.(mentioned in the above reference link)
  3. Based on that, our platform in the backend will itself, tries to receive the code grant, and keeps the referesh mechanism of access and refresh tokens going.

We have some of the sample codes available for you to checkout. Let me know if that helped you make some progress.

cc: @rohan15

Hi Saif/Team,

Thanks for the information and examples. I had created the oauth_config.json as suggested. However, through the serverless app , I’m getting “null” in the access_token tag-‘Authorization’ : ‘Bearer <%= access_token %>’ in the SERVER.js file.

However, when I hit the URL on Chrome Browser/Postman directly, it’s returning the correct response. Can you please suggest how we can resolve this in the FD serverless app?

Few more things, I noticed:
Through the app the URL being created is like this:
https://nor.com.mm/oauth/v1/userAuthorize?scope=read&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A10001%2Fauth%2Fcallback&state=8aaa7b35-15bb-4469-9b7f-e3c6d98d51c4&client_id=4v3etSEN0AsS1irW71XcCCB3QAsUUB8a
whereas it should actually be like this:
https://nor.com.mm/oauth/v1/userAuthorize?client_id=4v3etSEN0AsS1irW71XcCCB3QAsUUB8a&response_type=code&scope=READ

Secondly, When I opened this: http://localhost:10001/custom_configs, I can see the below error:
TokenError
at OAuth2Strategy.parseErrorResponse (C:\new\nvm\v10.18.0\node_modules\fdk\node_modules\passport-oauth2\lib\strategy.js:358:12)
at OAuth2Strategy._createOAuthError (C:\new\nvm\v10.18.0\node_modules\fdk\node_modules\passport-oauth2\lib\strategy.js:405:16)
at C:\new\nvm\v10.18.0\node_modules\fdk\node_modules\passport-oauth2\lib\strategy.js:175:45
at C:\new\nvm\v10.18.0\node_modules\fdk\node_modules\oauth\lib\oauth2.js:191:18
at passBackControl (C:\new\nvm\v10.18.0\node_modules\fdk\node_modules\oauth\lib\oauth2.js:132:9)
at IncomingMessage. (C:\new\nvm\v10.18.0\node_modules\fdk\node_modules\oauth\lib\oauth2.js:157:7)
at IncomingMessage.emit (events.js:203:15)
at endReadableNT (_stream_readable.js:1143:12)
at process._tickCallback (internal/process/next_tick.js:63:19)

Hi Saif/Team,

Basically, the error we are facing now in the above question is that I’m getting null value in the access token. We have done the below configuration for your reference:
{
“client_id”: “4v3etxxxxxxxxAsUUB8a”,
“client_secret”: “3yoj6xxxxxxxxby”,
“authorize_url”: “https://nor.com.mm/oauth/v1/userAuthorize”,
“token_url”: “https://nor.com.mm/oauth/v1/token”,
“options”: {
“scope”: “READ”
},
“token_type”: “account”
}

Hi @Saif/Team, Could you please provide some resolutions for the above posted questions? Please let us know if you need any more information from our side.

@rohan15, It might be the case that, in the request that you are trying to make, did you mention isOAuth:true in the req headers?

Similar to this,

var getFiles = function() {
  var self = this,
    path = "/",
    headers = { Authorization: "bearer <%= access_token %>"},
    reqData = { headers: headers, isOAuth: true },
    url = "https://api.onedrive.com/v1.0/drive/root:" + path +
              ":/children";
  client.request.get(url, reqData).then(
    function(data) {
      console.log(data);
      // var response = JSON.parse(data.response)["value"];
      // handleSuccess(response);
    },
    function(error) {
      console.log(error)
      //handleError(error);
    }
  );
}

Hi Saif, Yes we included isOAuth:true in the request as well. Please find below snippet used.
PS: We also tried setting headers in options, but that was also giving the same error.

exports = {

events: [
{ event: ‘onTicketCreate’, callback: ‘onTicketCreateHandler’ }
],

// args is a JSON block containing the payload information.
// args[‘iparam’] will contain the installation parameter values.
onTicketCreateHandler: function(args) {
console.log('Hello ’ + args[‘data’][‘requester’][‘name’]);

  $request.post(`https://prod-apigw.mytelenor.com.mm/v3/mm/en/communicationMessage/send`, {
  headers : {
    'Authorization' : 'Bearer <%= access_token %>', // Here, access_token is passed safely which is a secure installation parameter
      'content-type': 'application/json'
  },
  isOAuth : true,
  json: {   "type": "TEXT",   "content": "Hello Mingalar par%21 Welcome%2C Telenor",   "characteristic":[     {       "name":"UserName",       "value":"username"     },     {       "name":"Password",       "value":"password"     }   ],   "sender": {     "@type": "5",     "name": "Example"   },   "receiver": [     {       "@type": "1",       "phoneNumber": "959791001XXX"     }   ] }
})
	.then(function (data) {
		// TODO : Add try catch block
      console.log("Success "+data.status);  
     
		
	},
    function(error) {
        //handle failure
      
      console.error("error", error);
    }
         
         );

}

};

Any change we can do in the server.js or oauth_config.json file so that we can get the value in access_token in the FD serverless app? Had shared errors that we received in the above posts.

We checked separately via Postman Tool and the third party is returning the response correctly:

{
“status”: “approved”,
“accessToken”: “s2tzd08Gjme3PPyyJXKjBT0Uau8X”,
“refresh_token”: “oS5L5zAYC1EZc8GRAoU8sD1JDCGKR08C”,
“expiresIn”: “3599”,
“scope”: “”,
“tokenType”: “BearerToken”
}

Hi Saif/Team, on further debugging on hitting http://localhost:10001/custom_configs, after running fdk_run, we can see the below error. It seems the authorization code value is not populating. Any change required in the configuration in the above posts to resolve this?

authorization code is hy3rUXd7 and callbackURL is http://localhost:10001/auth/callback
authorization code is cbaPgYcS and callbackURL is http://localhost:10001/auth/callback
authorization code is 3coDVFOk and callbackURL is http://localhost:10001/auth/callback
authorization code is D4eZXAfe and callbackURL is http://localhost:10001/auth/callback
authorization code is 3ncav4cO and callbackURL is http://localhost:10001/auth/callback
authorization code is 3ncav4cO and callbackURL is http://localhost:10001/auth/callback

body
{
“code”: “401.000.2001”,
“error”: “Unauthorized”,
“message”: “Error :Invalid Authorization Code”
}

TokenError
at OAuth2Strategy.parseErrorResponse (C:\new\nvm\v10.18.0\node_modules\fdk\n
ode_modules\passport-oauth2\lib\strategy.js:362:12)
at OAuth2Strategy._createOAuthError (C:\new\nvm\v10.18.0\node_modules\fdk\no
de_modules\passport-oauth2\lib\strategy.js:409:16)
at C:\new\nvm\v10.18.0\node_modules\fdk\node_modules\passport-oauth2\lib\str
ategy.js:178:45
at C:\new\nvm\v10.18.0\node_modules\fdk\node_modules\oauth\lib\oauth2.js:191
:18
at passBackControl (C:\new\nvm\v10.18.0\node_modules\fdk\node_modules\oauth
lib\oauth2.js:132:9)
at IncomingMessage. (C:\new\nvm\v10.18.0\node_modules\fdk\node_mo
dules\oauth\lib\oauth2.js:157:7)
at IncomingMessage.emit (events.js:203:15)
at endReadableNT (_stream_readable.js:1143:12)
at process._tickCallback (internal/process/next_tick.js:63:19)

Hi Saif/Team , can we connect over call or some screen share to debug this issue? As it might be easier to resolve it this way?

@rohan15,

Are you still seeing access_token is being substituted by null?

Once access_token in substituted correctly, our platfrom will try to automatically perform OAuth mechanism of exchanging Authorization Codes and Tokens follwing the OAuth 2.0 Standard protocol.

The question is, does the OAuth provider at your end follows the Standard protocol? It should be part of the instructions that you are following to reproduce the OAuth flow manually.

Can you respond to my private message on this forum inbox where I requested for the OAuth Spec document that you folks are following?

Hi Saif, yes, we are not getting the value in access_token. OAuth2 authentication via HTTPS is being followed. I am checking with my team if we are allowed to share the specification document and will update you.
However, is it possible that we have a call and screenshare today to show you guys the exact issue? It might become clearer then as we are facing this issue in the serverless app but when we try via Postman tool it is working.

Sure @rohan15,

Please check with your team.

Only confirmation that you need to have is that if the 3rd party OAuth provider has implemented OAuth handshake differently than RFC 6749 protocol. This platform feature may not work.

Postman can make it work because you only try to send request. Unlike platform that performs the complete handshake on behalf of the app. On top of you, developer mentions the Access tokens directly without programmatically being fetched.

Please keep me posted me the update regarding the Standard protocol. We will on top of it see if a call can be beneficial for both of our time.

Hi Saif, we checked with third party team and they have said that they are following RFC 6749 protocol and authorization code in grant type.

@rohan15 Thank you for patiently working through this problem.

I strongly feel it would help if we see a brief description of the problem you are trying to solve. Perhaps what you are trying to do is not the right way to achieve it on our platform. We can help you choose the right solution and then work toward solving issues with implementing the same.

Could you please describe in brief what you are actually trying to do in this app? Feel free to leave out details that might be business-specific - but we would want to understand what the app needs to do in terms of acting on events and what kind of authentication is expected by the endpoints you are hitting.

Hi Satwik, what we are trying to do is build an FD serverless app which calls a SMS sending API which requires Oauth2 authentication to be accessed. The process is given below:

  1. On ticket creation event, FD serverless app to make a call to authorization API and be redirected to a callbackurl with authorization code.
  2. Take authorization code and make a call to Token Generation URL.
  3. Use this token and call the actual API for sending SMS.

As suggested by Saif, we have made use of FD’s platform feature for using Oauth2:

  1. We have registered the callbackURL as http://localhost:10001/auth/callback on the third party’s portal.
  2. We have created a serverless app and have created oauth_config.json file in the app’s config/ folder.
  3. We have whitelisted the API endpoint in Manifest File.
  4. We have run fdk run on command prompt.
  5. We have invoked the SMS sending API from server.js file by using $request.post.

The issue we are facing now, is that in requets_token we are not getting the value of the token.code in our server.js file. Some of the error screenshots can be screen if you see the previous posts.

We are getting null in the token in FD app. Therefore, we have scheduled a call with Saif tomorrow to debug this issue, as we had discussed this usecase with him previously on the portal.

Basically we want to know if any additional configuration/code has to be written for getting the token?

1 Like