function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
VINAY KAUSHIK 14VINAY KAUSHIK 14 

Access Token without using username and password

Hi Guys,
How can we get the access token without passing the username and password? Also, is there any other way to get the access token from the session id or based on login?
 

GovindarajGovindaraj
Hi Vinay,

You can use userInfo class for that,

Below is the sample code,
HttpRequest req = new HttpRequest();
        req.setEndpoint('<Endpoint>');
        req.setMethod('GET');
         
        //Get SessionId
        string autho = 'Bearer '+userInfo.getSessionId();
        req.setHeader('Authorization', autho);
         
        //Get Response
        Http http = new Http();
        HTTPresponse res= http.send(req);
        string response = res.getBody();
Please let us know, if this helps.

Thanks,
Govindaraj.S
Raj VakatiRaj Vakati
The above Solution may not work .. because to get the session Id you need to pass the user name and password .. 

You should be able to do this without username/password using oauth 2.0.

Refer this link 

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


https://help.salesforce.com/articleView?id=remoteaccess_authenticate.htm&type=5

https://help.salesforce.com/articleView?id=remoteaccess_oauth_web_server_flow.htm&type=5
 
req.setEndpoint('https://ap1.salesforce.com/services/oauth2/token');

req.setHeader('Content-Type','application/x-www-form-urlencoded');

req.setbody('xmlstring');

req.setMethod('GET');

req.setbody('grant_type=authorization_code&client_id=client id&client_secret=secrete 

key&redirect_uri=https://www.runscope.com/oauth_tool/callback');

HttpResponse res = h.send(req);


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
VINAY KAUSHIK 14VINAY KAUSHIK 14
Thanks for your response. Also, @Raj Vakati would like to know how we can get the authorization code from, to set it in the grant type?
Raj VakatiRaj Vakati
authorization_code is one of the grant_type if you want to pass the client and sec to get the access token .. 
This is the best link to understand oauth 

https://developer.salesforce.com/index.php%3Ftitle%3DDigging_Deeper_into_OAuth_2.0_on_Force.com%26oldid%3D50717