With Microsfot leaving basic authentication behind it is unsecure to use username and passwords anymore. Authentication with Client ID and Secrets is the suggested and secured method to use. We will look at how to do this for SharePoint Online API. First we will register an app on SharePoint site, use its ID and Secret to authenticate. So let’s begin.
Register the Add-in SharePoint using AppRegNew form
- Navigate to <site collection url>/_layouts/15/AppRegNew.aspx

Enter values for the follow form fields:
- Add-in ID. Also known as client ID; a GUID that can be generated (when you select Generate) or pasted into AppRegNew.aspx. The value must be unique for each add-in, and must be lowercase.
- Add-in Secret. Also known as the Client Secret, an opaque string. It is generated on the AppRegNew.aspx page by using the Generate button.
- Title. A title for the add-in. This title appears as the name of the add-in on the consent prompt.
- Add-in Domain. For token generation add-in, fill in any value without https or slashes(/).
- Redirect URI:. For token generation add-in, fill in any value.

You will be navigated to a page displaying the details of your add-in. You need to save Client Id & Client Secret.
Grant Permission to the newly created Principal
We still need to add permissions to the add-in we just created.
Navigate to <site collection url>/_layouts/15/appinv.aspx
Use your generated Client Id in App Id text box and click Lookup. You app details will be loaded.
In the Permission Request XML box you’ll need to provide the permission XML that describes the needed permissions. To construct that XML, check the official Microsoft docs here

When you click on Create you’ll be presented with a permission consent dialog. Press Trust It to grant the permissions:

You can navigate to the <site collection url>/_layouts/15/appprincipals.aspx to also confirm that the permission has been assigned to the add-in.