Monday, 13 May 2019

Named Credentials in Salesforce

Authentication vs Authorization :
==================================

Authentication is who are you, what's your identity,can you prove you are who you say you are.

Authorization is what can you access,what sort of privileges doyou have,what resources can you get your hands on.

TLS and HTTPS Mechanics :
========================
A secure way to transmit information, which a lot of the modern security of the web is built on.


OAuth :
=========
salesforce support 9 OAuth flows.
1.its a authorization framework .

OAuth Endpoints in Salesforce :
===============================
Authorization : https://login.salesforce.com/services/oauth2/authorize
Token Request : https://login.salesforce.com/sevices/oauth2/token


Basic OAuth Flows :
======================

where I'm identifying both the owner
and the client.

1.user agent flow
2.Implicit flow
3.password flow
4.client credentials flow

Note : client credentials is really when
you have two servers or two applications
that are talking directly without the
context of a user.

Calling out from Salesforce :
===============================
Communcation begins at salesforce side which is call outbound/callout.

ex : Apex callouts
     Platform events
     external dataobjects
     soap/rest calls

Named Credentials :
======================

A named credential specifies the URL of a callout endpoint and its required authentication parameters in one definition.

ex :
request.setEndpoint('callout:EndPointURL');

where "EndPointURL" is the Name of the Credentials

Benefits of using Named Credentials :
======================================
1.Authentication is done by Salesforce and you need not worry about that.
2.No need to create a Remote Site Setting if using a Named Credentials.
3.Callouts is easier to maintain. No hard Coding involved.
4.if you are using Sandboxes for callouts ,just create the Named Credentials with the same Name and save different URL.
5.Use Merge fields for Custom Authentication.

when to use Named Credentials :
================================

integration within the same salesforce org or any other salesforce org (Kind of salesforce to salesforce) or any other webservice vendor.

Identity Type :
=================
1.Anonymous :
No identity and therefore no authentication.

2. Per User :

Use separate credentials for each user who accesses the external system via callouts.
select this option if the external system restricts access on a per-user basis.

After you grant user access through permission sets or profiles in Salesforce, users can manage their
own authentication settings for external systems in their personal settings.

3. Named Principal :

Use the same set of credentials for all users who access the external system from your
organization.Select this option if you designate one user account on the external system
for all your salesforce org users.

Note :
======
if the callout specifies a named credential as the endpoint, you don't need to configure
remote site settings.

Query :
========
SELECT DeveloperName, Endpoint FROM NamedCredential

The NamedCredential object has a field named "EndPoint".

Oauth token used in Named credentials :

ex : req.setHeader('Authorization', 'Bearer {!$Quickbooks.OAuthToken}');


Authentication Protocol :
=========================
Salesforce supports two types of authentication protocols
1.Password Authentication(Basic Authentication)
2.OAuth 2.0

The Password authentication is pretty straightforward: it uses BASIC authentication
(username/Password BASE64 encoded sent in the header).

OAuth Protocol

To connect with another salesforce,connected app needs to be created in one ORG and
Auth.Provider & Named Credentials need to be configured in another org.

Authentication Providers :
===========================

Salesforce supports some authentication providers.

1.Facebook
2.Janrain
3.Google
4.LinkedIn
5.Salesforce
6.Open ID Connect
7.Microsoft Access Control Service
8.Twitter
9.GitHub
10.CustomAuthProvider

Note : Auth Provider acts as junction between Named Credentials and Connected App.

Connected apps :
=================
1.Connected app used for making connection form outside to salesforce.

clientid,client screct,
authorization endpoint url,
token endpoint url

ex: For accessing salesforce from third party app, a connected app can be used by them to make a connection and access Salesforce.



ex :

@AuraEnabled
Public static void serverSendMessage( String selectedCredential, String message){

  HttpRequest req = new HttpRequest();
  req.setMethod('POST');
  req.setEndpoint('callout:' + selectedCredential);
  req.setHeader('Api-Key','{!$Credential.Password}'); // merge field
  req.setBody(message);
 
  new Http().send(req);

}

Note :
1.Remote Site settings enables callout to external site(from Salesforce),when site url is added to remote site setting.

ex: For making callout to a external URL, it must be registered to remote site.otherwise the call would simply fail.

Client Credentials Flow :
=========================
Client credentials is a very popular flow for when two servers are interacting with each other directly and there's no user context involved.


Custom Authentication Provider :
================================

public with sharing class CustomAuthProvider extends Auth.AuthProviderPluginClass
{



 private static String redirectUrl = 'https://fun-connect-1108-dev-ed.cs65.my.salesforce.com/services/authcallback/Custom';



 public String getCustomMetadataType()
 {

   return 'Auth__mdt';

 }



 public PageReference initiate(Map<String, String> config, String stateToPropagate)
 {

   System.debug(LoggingLevel.WARN, 'initiate-config: ' + config);

   System.debug(LoggingLevel.WARN, 'initiate-stateToPropagate: ' + stateToPropagate);

   String url = config.get('Token_Endpoint__c');

   url += '?redirect_uri=' + redirectUrl + '&state=' + stateToPropagate;

   return new PageReference(url);

 }



 public Auth.AuthProviderTokenResponse handleCallback(Map<String, String> config, Auth.AuthProviderCallbackState callbackState)
 {

   System.debug(LoggingLevel.WARN, 'handleCallback-config: ' + config);

   System.debug(LoggingLevel.WARN, 'handleCallback-callbackState: ' + callbackState);

   System.debug(LoggingLevel.WARN, 'handleCallback-token: ' + callbackState.queryParameters.get('token'));

   return new Auth.AuthProviderTokenResponse('PbP', callbackState.queryParameters.get('token'), null, callbackState.queryParameters.get('state'));

 }



 public Auth.UserData getUserInfo(Map<String, String> config, Auth.AuthProviderTokenResponse response)
 {

   System.debug(LoggingLevel.WARN, 'getUserInfo-config: ' + config);

   System.debug(LoggingLevel.WARN, 'getUserInfo-response: ' + response);

   return new Auth.UserData('fakeId', 'first', 'last', 'full', 'email', 'link', null, null, null, null, null);

 }



 public override Auth.OAuthRefreshResult refresh(Map<String, String> config, String refreshToken) {

  System.debug(LoggingLevel.WARN, 'refresh-config: ' + config);

  System.debug(LoggingLevel.WARN, 'refresh-refreshToken: ' + refreshToken);

  return null;

 }


}

No comments:

Post a Comment