In the integration of Google Docs, I used a credential file to provide client Id and keys. However, sensitive data should not be used directly in codes. This blog is to use IOptions in ASP.Net to achieve this.
There are 4 steps:
- create a class to store sensitive data
- set up appsettings.json
- register in startup.cs
- use the sensitive data
1. create a class to store sensitive data
public class GoogleDocSettings
{
public string ApplicationNameSetting { get; set; }
public string TemplateDocId { get; set; }
public string ClientId { get; set; }
public string ClientSecret { get; set; }
}
2. set up appsettings.json
"googleDoc": {
"applicationNameSetting": "Google Docs API",
"templateDocId": "188888888888888************80c",
"clientId": "597*******1-g*************q.apps.googleusercontent.com",
"clientSecret": "l**********P"
}
3. register in startup.cs
services.Configure<GoogleDocSettings>(options =>
Configuration.GetSection("googleDoc").Bind(options));
4. use the sensitive data
private readonly GoogleDocSettings googleDoc;
public GoogleService(
IOptions<GoogleDocSettings> googleOptions)
{
this.googleDoc = googleOptions.Value;
}
public async Task<bool> UseGoogleDocs(DemoViewModel model)
{
try
{
UserCredential credential;
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets { ClientId = googleDoc.ClientId,
ClientSecret = googleDoc.ClientSecret },
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
// Create Google Docs API service.
var service = new DocsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = googleDoc.ApplicationNameSetting,
});
var serviceDrive = new DriveService(
new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = googleDoc.ApplicationNameSetting,
});
// rest codes...
That is it!