0

Hi everyone,

basically, I'm new to salesforce, I'm making the rest API using Apex. is there any way to validate the access token, I know we can set up the limit for the token expiration in the org, but how to handle it from the code level?

For an example

My token got expired then is there any way to handle it? currently my execution is not reaching to the method seems salesforce itself throwing an execption.

any help will be highly appreciated.

konowo7640
  • 23
  • 1
  • 6

1 Answers1

1

You're writing Apex code that's exposed as REST service, with @RestResource etc? In that code you don't have to worry about authorisation. If the code runs - Salesforce already validated the session id, found the user, verified that this user has access to this class, that the session id was created with good OAuth2 scope etc.

If you're talking about external application that logs in and calls this custom service - well. You'd need to pick right OAuth2 flow to log the user in (you tagged it communities so "username password flow" for example won't work, you'll likely need "web server flow" or "user agent flow". For example this one returns "issued at" but it doesn't mean much, it doesn't automatically mean that session is valid for X hours. As user keeps interacting with the app the session timeout gets reset; on other hand an IP change could kick you out, admin could suspect hacking and kick you out using Setup -> Session Management...

Best you can do is code defensively. Make a request with last known session id you got, if it returns something like 401 Unauthorised - call login procedure (if you're really doing it in community - redirect them to login screen with callback url pointing back to the action you wanted to do), wait for user to complete login and retry the operation? There are many reasons you might be getting authorisation failure, check https://stackoverflow.com/a/72172355/313628 for start.

eyescream
  • 18,088
  • 2
  • 34
  • 46
  • if you're unable to get the code to run via API at all - check https://stackoverflow.com/a/69810951/313628 for tips on doing the "OAuth2 dance" manually and once you get a valid access_token - try to make a request in Postman or something manually before moving on to coding it in your app. – eyescream May 16 '22 at 17:49
  • Thank you for your response, I'll try this callback URL – konowo7640 May 17 '22 at 13:06