1

I have written this Apex code to get access token:

private static OAuth getAccessToken(){
    try{
        HttpRequest req = new HttpRequest();
        req.setEndpoint(ENP_POINT_URL);
        req.setMethod('POST');          
        Blob headerValue = Blob.valueOf(USERNAME + ':' + PASSWORD);
        String authorizationHeader = 'BASIC ' +
        EncodingUtil.base64Encode(headerValue);
        req.setHeader('Authorization', authorizationHeader); 
        req.setBody(String.format(REQUEST_BODY ,new string[]{CONSUMER_KEY,CONSUMER_SECRET,
                                                             USERNAME,PASSWORD}));
        req.setTimeout(60000);
        Http http = new Http();
        HttpResponse res = http.send(req);
        System.debug('res.getbody() - >' + res.getbody());

        OAuth objAuthenticationInfo = (OAuth)JSON.deserialize(res.getbody(), OAuth.class);
        return objAuthenticationInfo;
    }catch(CallOutException ce){
        throw ce;
    }

}



public class OAuth{
    public String id{get;set;}
    public String issued_at{get;set;}
    public String instance_url{get;set;}
    public String signature{get;set;}
    public String access_token{get;set;}    
}  

But as I have seen in all the examples and read all the blogs it is necessary to pass UserName and Password of to generate an access token, and this has to be hardcoded.

Is there a way to make this dynamic, as the User might not be present in another org.

I am generating the access token and firing a get request to a webservice hosted in heroku.

String AccessTokenFromOauthObject= AuthenticationDetail.authenticationDetail.access_token;
String InstanceURLFromOauthObject= AuthenticationDetail.authenticationDetail.instance_url;
system.debug('InstanceURLFromOauthObject-->'+InstanceURLFromOauthObject);
Http http = new Http();
Httprequest  req = new Httprequest();
req.setheader('Authorization','Bearer '+AuthenticationDetail.authenticationDetail.access_token);
req.setendpoint('https://***.herokuapp.com/****/merge?params*****');
req.setmethod('GET');

Httpresponse res = http.send(req);
system.debug(res.getbody());
0

3 Answers 3

1

Depending on what OAuth flows are supported by the service you are connecting to, you may be able to use the Client Credentials flow, since you are effectively connecting machine to machine.

From https://alexbilbie.com/guide-to-oauth-2-grants/

Client credentials grant (section 4.4)

The simplest of all of the OAuth 2.0 grants, this grant is suitable for machine-to-machine authentication where a specific user’s permission to access data is not required.

The Flow

The client sends a POST request with following body parameters to the authorization server:

  • grant_type with the value client_credentials
  • client_id with the the client’s ID
  • client_secret with the client’s secret
  • scope with a space-delimited list of requested scope permissions.

The authorization server will respond with a JSON object containing the following properties:

  • token_type with the value Bearer
  • expires_in with an integer representing the TTL of the access token
  • access_token the access token itself

However, if the service you are connecting to has no support for the client_credentials grant type (Salesforce, for example, does not support this flow) then you will have to either store usernames and passwords, or redirect the user through the more common authorization_code flow.

Alternatively

Depending on your needs, you may find that Named Credentials could work for you, as they take care of a lot of this stuff for you, and you don't need to worry about storing user credentials yourself: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_callouts_named_credentials.htm

1
  • Yes I think this is what I was looking for, Named Credentials. Jun 9, 2018 at 1:30
1

You should be able to do this without username/password using oauth 2.0. I'm going to avoid getting to nitty gritty into how oauth works since this is a SF Q&A board. You can get some great details from http://oauthbible.com/ If you have Oauth specific questions you can try https://stackoverflow.com

The general idea is that instead of passing in a username/password you get a request token, then forward the user to a login page with the request token. The user logs in with their username/password, approves the requested permissions and then an access token and user are redirected back to what ever url you provide as the callback. You then store this access token and use it for future call-outs.

Oath flow

The oauth bible page should guide you through what you need to provide in the header at each step and what you can expect to get back from the calls you make.

Connected Apps

You'll need to set up a connected app in SF as well to help process the transaction if you haven't already. Here's a great article on how to do that.

Disclaimer

Normally I'd try to quote the relevant material but there is just so much material that is relevant that it doesn't make sense to quote it here. If the links die, OAuth 2.0 is likely not in use anymore and this answer is no longer valid.

5
  • Thanks for the detailed answer, but I know how connected app works. The issue is I wanted to do this programmatically. To this programmatically, I think there is no way to get access token without UserName and Password. In short I would like to generate Access_Token without user interaction. Jun 8, 2018 at 1:01
  • 1
    What you want is not secure.
    – gNerb
    Jun 8, 2018 at 14:48
  • Same here. i'm curious if there's a way to get the accessToken programatically without the username and password.
    – JPG
    Aug 4, 2020 at 14:37
  • I believe, while its not programmatic, since this question was asked, sfdc has added a feature to connected apps where you can simply generate a token via the UI and provide that token to your integrated app. This prevents the need for a username/password.
    – gNerb
    Oct 22, 2020 at 18:42
  • @gNerb do you know where this can be found? Jan 13, 2021 at 17:38
0

Depending on your needs you could consider the "JWT Bearer Flow". This works without any user interaction, login/password flow.

https://help.salesforce.com/s/articleView?id=sf.remoteaccess_oauth_jwt_flow.htm&type=5

1
  • Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.
    – identigral
    Jul 13, 2022 at 23:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .