[SalesForce] How to incorporate Consumer id and consumer secret in the REST API (Apex class)

I have a requirement where some external web forms would be calling our REST API to submit Lead. I have created a connected app, got the consumer id and consumer secret. I want my apex class to be accessible only to those people who have the consumer key and consumer secret. In other words, the lead should only be created if the incoming request has consumer key and consumer secret.

This is my code right now:

@RestResource(urlMapping='/api/createLead')

global with sharing class RESTAPI_JSONPayload 
{


@HttpPost
global static void doPost() {
  RestRequest req = RestContext.request;
  Blob body = req.requestBody;
  String requestString = body.toString();
  String ContentType = RestContext.request.headers.get('Content-Type') ;
//Now as you have the request string You can parse it in APEX

  JSON2Apex rw = (JSON2Apex)JSON.deserialize(requestString,JSON2Apex.class);
  .......
  .......
  ........

Right now, I have been testing it with POSTMAN tool in 2 steps:

Making a POST request first with username, password, client_id, client_secret, grant_type to receive access token.

Then I make another POST request in POSTMAN to create a lead in Salesforce, using the access token I received before and the body.

Questions:

I wonder since I have not incorporated consumer key and consumer secret in my code above, how does that REST class got connected to my "Connected app" in Salesforce and the specific Consumer key and secret coming from the connected app?

Secondly, do I need to provide port number and callback url in my code above? Or whatever I have is fine?

Best Answer

I wonder since I have not incorporated consumer key and consumer secret in my code above, how does that REST class got connected to my "Connected app" in Salesforce and the specific Consumer key and secret coming from the connected app?

You need a valid "access token" to be able to access your API resources. And that you got this by authenticating and authorizing your connected app by using the combination of your consumer key/secret, username, etc. The API is not aware how you retrieved the "access token". So as long as you have one, you will be always be able to access your API.

Secondly, do I need to provide port number and callback url in my code above? Or whatever I have is fine?

The Callback URL is utilized in a Connected App to be able for Salesforce to send the access token to a particular location.

Depending on which OAuth flow you use, this is typically the URL that a user’s browser is redirected to after successful authentication. As this URL is used for some OAuth flows to pass an access token, the URL must use secure HTTP (HTTPS) or a custom URI scheme.