Tuesday, 11 March 2014

Authentication (Get Accesss token and Signature) of Salesforce using Apex

Authentication of Salesforce to perform an action on behalf of the User from out side the system or from the different Salesforce Org.
To retrieve records or perform an action in Salesforce on behalf of a user then we need to get connect with Salesforce there are several ways to connect with Salesforce, One and important method is OAuth using username and password to get access token and call out on the Salesforce org.

An autonomous client can obtain an access token by simply providing username, password and (depending on configuration) security token in an access token request. Again the request is POSTed (1) to https://login.salesforce.com/services/oauth2/token or https://test.salesforce.com/services/oauth2/token, but the payload now has the form

grant_type=password&client_id=<your_client_id>&client_secret=<your_client_secret>&username=<your_username>&password=<your_password>

The following parameters are required:
grant_type Set this to password.
client_id         Your application's client identifier (How to generate consumer key).
client_secret Your application's client secret (How to generate secret key).
username The API user's Salesforce.com username, of the form user@example.com.
password The API user's Salesforce.com password. If the client's IP address has not been white listed in your org, you must concatenate the security
token with the password.

You will receive a similar response to the authorization code case: Demo 

{
    "id":"https://login.salesforce.com/id/00D50000000IZ3ZEAW/00550000001fg5OAAQ",
    "issued_at":"1296509381665",
    "instance_url":"https://ap1.salesforce.com",
    "signature":"aNbl5EOl/DlsvUZ4NbGDno6vn935XsWGVbwoKyXHayo=",
    "access_token":"120D50000000IZ3Z!AQgAQH0Yd9M51BU_rayzAdmZ6NmT3pXZBgzkc3JTwDOGBl8BP2AREOiZzL
                    _A2zg7etH81kTuuQPljJVsX4CPt3naL7qustlb"
}
You will notice that there is no refresh token in the response. Since the user is not redirected to login at Salesforce, there is no opportunity
for the user to authorize the application. Such an authorization is required for a refresh token to be issued. If your application requires a
refresh token, you should carefully consider moving to either the web server or user agent flow if at all possible.

Generic Apex Class to get Authentication Detail(Just copy and paste in your org and you are ready to use the class) :

/*
    @Author: Mohammad Usman
    @Description: Class is used to get Authentication of salesforce
    @version:1.0
*/
public with sharing class AuthenticationDetail{
    /*End point Url to web service callout*/
    private final static String ENP_POINT_URL = 'https://login.salesforce.com/services/oauth2/token';
    //For development and production https://login.salesforce.com/services/oauth2/token
    //And for sandbox https://test.salesforce.com/services/oauth2/token
    private final static String REQUEST_BODY = 'grant_type=password&client_id={0}&client_secret=
                                                {1}&username={2}&password={3}';
    private final static String USERNAME = 'Your_Username';
    private final static String PASSWORD = 'Your_Password';
    private final static String CONSUMER_KEY = 'Your_Org_Consumer_Key';
    private final static String CONSUMER_SECRET = 'Your_Org_Consumer_Secret';
    
    /*To generate Access token Method*/
    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);
            OAuth objAuthenticationInfo = (OAuth)JSON.deserialize(res.getbody(), OAuth.class);
            return objAuthenticationInfo;
        }catch(CallOutException ce){
            throw ce;
        }
        return null;
    }
    
    /*To get Access token property*/
    public static OAuth authenticationDetail{
        get{
            if(authenticationDetail == null){
                authenticationDetail = getAccessToken();
            }
            return authenticationDetail;
        }set;
    }
        
    /*To get aouthentication detail Wrapper*/
    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;}    
    }   
}
Output of the above Class:

Authentication Detail for the above apex class
Summary :
Force.com's implementation of OAuth 2.0 allows client applications to access resources on behalf of end users without sharing credentials such as passwords with those client applications, enhancing both privacy and security. This article provides a description of OAuth as well as the various authentication flows supported by OAuth.

Reference :
http://wiki.developerforce.com/page/Digging_Deeper_into_OAuth_2.0_on_Force.com

No comments:

Post a Comment