[SalesForce] Best way to get Session ID or oAuth Access Token

What is the best way to get Session ID or oAuth Access Token, without having to use password in Apex Code (or) in custom settings (or) Named Credentials?

Will one of the oAuth flows work in this case?
(obviously username-password flow cannot be considered since it involves passing the password as part of URL)

Here's the use case i am trying to achieve:

  • I am trying to call the MetaData api of salesforce using the metadata
    api wrapper available on GitHub. Using this i am trying to find
    out, metrics like number of custom fields, number of test classes,
    number of classes etc.
  • This process should run in a scheduled batch apex job. In order
    to call metadata api, i need to pass the sessionid. I used
    UserInfo.GetSessionID in my batch apex class but that doesn't work as
    per my research and also tried it.
  • The other option is to call the login service to get the session id
    or access token, which i can further use to make subsequent calls to
    metadata api. All the research i did points mostly to articles where
    the REST api is called to get access token by using connected app
    credentials, but all of these involve passing password as an
    attribute to get the access token.
  • So i figure oauth is better way to go and am basically trying to find
    out the best way(oAuth flow) to get access token without needing
    to use a Salesforce User's password. And any helpful articles for the
    same to build this.

Best Answer

1. OAuth 2.0 Flow

To authenticate you also have option to show Salesforce login screen for user authentication.

There will be just bit of modifications in the http callouts.

When you request for access token using URL 'https://login.salesforce.com/oauth_callback?code=<value-you-got-in-prev-callout>&state=<whatever_you_sent_in_step_2>' do not make http callout instead redirect user to that url, After successfully logging in you will get access token and refresh token that you can use further.

Reference : https://developer.salesforce.com/page/Digging_Deeper_into_OAuth_2.0_on_Force.com

2. OAuth 2.0 Refresh Token Flow

If you are using a Scheduler/Batch class then the best way would be to authenticate the org before starting the job and then storing the refresh token in a custom setting. Then in each batch execution you can use the refresh token to get a valid access token. This is way much better way than storing the user name and password.

If you really don't want to use a custom setting to store the refresh token it could be passed in as a parameter.

OAuth 2.0 Refresh Token Flow

3. Using Session Id

Check this old question : She is also tring to authenticate from Scheduler. How to get UserInfo.getSessionId() in Scheduler/Batch

Related Topic