Instead of using a service account with username and password, would suggest that you connect and authenticate to SharePoint online by using Client Id and Secret according to this documentation.
It will be a one-time setup with the below mentioned steps:
1) Go to your SharePoint online site collection
2) Enter the URL as https://<tenant-name>.sharepoint.com/sites/test/_layouts/15/appregnew.aspx
3) On that page, we will generate the Client ID and Secret
4) Add the Title as some "SSO Auth"
5) Enter App domain as localhost
and Redirect URL as https://localhost
.
6) Then click on create. Save the client ID and Secret in a local file or notepad. It should look something like:
Once the above step is done, go to https://<tenant-name>.sharepoint.com/sites/test/_layouts/15/appinv.aspx
1) In the App id, enter the Client Id that we generated in the previous step and then click on [lookup]
2) In the Permission Request XML section, enter the below XML code:
<AppPermissionRequests AllowAppOnlyPolicy="true">
<AppPermissionRequest Scope="http://sharepoint/content/sitecollection" Right="FullControl" />
</AppPermissionRequests>
3) Click on [Create]. See below screenshot
4) After that, it will redirect you and on that page, click on the [Trust It] button.
Once the above steps are done, in your application, download the SharePoint PnP core
package from nuget as below:
After that, you can use PnP's Authentication Manager's method to authenticate as below:
var clientID = "<your-client-id>";
var clientSecret = "<your-client-secret>";
var authManager = new OfficeDevPnP.Core.AuthenticationManager();
ClientContext clientContext = authManager.GetAppOnlyAuthenticatedContext("https://<tenant-name>.sharepoint.com/sites/test/", clientID, clientSecret);