Google API 사용을 인증하는 방법은 다음과 같습니다.
Private Function DoAuthentication(ByRef rStrToken As String, ByRef rParameters As OAuth2Parameters) As Boolean
Dim credential As UserCredential
Dim Secrets = New ClientSecrets() With {
.ClientId = m_strClientID,
.ClientSecret = m_strClientSecret
}
m_Scopes.Add(CalendarService.Scope.Calendar)
Try
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(Secrets, m_Scopes,
"user", CancellationToken.None,
New FileDataStore("XXXXX.Application")).Result()
If credential.Token.IsExpired(Google.Apis.Util.SystemClock.Default) Then
credential.RefreshTokenAsync(CancellationToken.None)
End If
' Create the calendar service using an initializer instance
Dim initializer As New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = "xxx"
}
m_Service = New CalendarService(initializer)
rStrToken = credential.Token.AccessToken.ToString()
rParameters.AccessToken = credential.Token.AccessToken
rParameters.RefreshToken = credential.Token.RefreshToken
Catch ex As Exception
' We encountered some kind of problem, perhaps they have not yet authenticated?
' Can we isolate that as the exception?
m_logger.Error(ex, "DoAuthentication")
Return False
End Try
Return True
End Function
그리고 내 Main
:
Dim parameters As New OAuth2Parameters
If (DoAuthentication(strToken, parameters)) Then
iResult = RESULT_SUCCESS_OAUTH
Else
Return RESULT_FAILED_OAUTH
End If
그런 다음 계속됩니다. 문제는 때때로 "인증"이 성공하더라도 나머지 코드를 실행하기 시작한다는 것입니다. 그런 다음 예외가 발생합니다.
2020-11-30 18:47:03.6762|ERROR|GoogleAuthandSync.Program|AddEventsToCalendarXML|System.IO.IOException: The process cannot access the file 'C:\Users\USERNAME\AppData\Roaming\XXXXX.Application\Google.Apis.Auth.OAuth2.Responses.TokenResponse-user' because it is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
토큰을 인증 / 갱신하고이 예외가 중지되도록 진행할 준비가되었는지 확인하려면 어떻게해야합니까? 항상 그런 것은 아닙니다.
(위의 코드 / 오류 텍스트에서 보안을 위해 토큰 파일의 이름을 변경했습니다).
Await
키워드를 사용해야합니까 ?
If credential.Token.IsExpired(Google.Apis.Util.SystemClock.Default) Then
Await credential.RefreshTokenAsync(CancellationToken.None)
End If
그게 차이를 만들까요? 나는이에 통지 샘플 코드 가 사용 await
.
나는 GitHub에서 문제에 대해 물어볼 것을 권했다 ( 토론 참조 ).
내가 그랬던 것처럼 사용할 필요가 없다는 RefreshTokenAsync
것이 밝혀졌습니다. 내 코드를 단순화하고 다음과 같은 Async
방법 으로 바꿀 수 있습니다 .
Private Async Function DoAuthenticationAsync() As Task(Of Boolean)
Dim credential As UserCredential
Dim Secrets = New ClientSecrets() With {
.ClientId = m_strClientID,
.ClientSecret = m_strClientSecret
}
Try
credential = Await GoogleWebAuthorizationBroker.AuthorizeAsync(Secrets, m_Scopes,
"user", CancellationToken.None,
New FileDataStore("XXXXX.Application"))
' Create the calendar service using an initializer instance
Dim initializer As New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = "XXXXX"
}
m_Service = New CalendarService(initializer)
Catch ex As Exception
' We encountered some kind of problem, perhaps they have not yet authenticated?
' Can we isolate that as the exception?
m_logger.Error(ex, "DoAuthentication")
Return False
End Try
Return True
End Function
그런 다음 Main
함수에있는 모든 코드를 작업으로 이동해야했습니다.
Private Async Function Run() As Task(Of Integer)
...
End Function
마지막으로 다음 Main
과 같이 조정 했습니다.
Public Function Main() As Integer
Return RunAsync.Result
End Function
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다