.NET Google api1.7 베타 인증으로 새로 토큰
-
21-12-2019 - |
문제
나왔습 Oauth.Net Google Api 하기 위해 인증을 통해 OAuth 고 사용하는 Google 드라이브 일으킬 수 있습니다.
특히,나는 사용하려면 새로 토큰 이미에 저장되고 사용하기 위해 인스턴스화 탐색 서비스입니다.
는 것을 사용하여"GoogleWebAuthorizationBroker.AuthorizeAsync"하지만 난 어떻게 사용할 수 있는 방법으로 새로 토큰보다는 클라이언트에 비밀이 있을 것,그것을 먹이에 이은 예입니다.
해결책
제가 올바르게 이해하면 기존 새로 고침 토큰을 기반으로 새 Google 서비스를 만들 수있는 방법을 묻는 메시지가 표시됩니다.
그래서 다음을 수행 할 수 있습니다.
var token = new TokenResponse { RefreshToken = "YOUR_REFRESH_TOKEN_HERE" };
var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = [your_client_secrets_here]
}), "user", token);
.
그런 다음 자격 증명을 서비스의 이니셜 라이저에 전달할 수 있습니다.
위를 수행하면 googleAuthorizationCodeFlow 은 토큰 및 클라이언트 비밀을 새로 고치는 새 액세스 토큰을 얻습니다.
여기에 클라이언트 비밀이 있어야합니다.이 없이는 액세스 토큰을 얻을 수 없습니다.
다른 팁
client_secrets.json에는 클라이언트 ID 및 클라이언트 비밀 (응용 프로그램에 대한 OAuth 2.0 정보가있는 정보가 있음)이 들어 있습니다.
이 기사는 웹 응용 프로그램을 구축하는 경우 특히 Google Apps API에 액세스 할 수있는 OAuth 2.0을 더 잘 설명 할 것입니다.
https://developers.google.com/accounts/docs/oauth2webserver
코딩 예제에 관심이있는 경우, stackoverflow에 하나가 있습니다. Google+ API : 앱이 시작될 때마다 액세스를 요청하지 않으려면 RefreshToPens를 사용하려면 어떻게합니까?
GoogleWebauthorizatization 브로커는이 경우 FileDataStore가 전송되는이 경우 IDAtastore의 암시를 보내야합니다.FileDataStore는 % appdata %의 데이터를 저장합니다.다시 refreshToken을 사용하려는 경우 다른 곳에서는 다른 위치를 작성해야합니다.
실제 데이터 저장소의 코드는 여기에 게시하기까지 조금 오래되었습니다. http://daimto.com/google-auth2-csharp/
당신은 당신이 filedatastore
처럼 그것을 사용합니다.//Now we load our saved refreshToken.
StoredResponse myStoredResponse = new StoredResponse(tbRefreshToken.Text);
// Now we pass a SavedDatastore with our StoredResponse.
using (var stream = new FileStream("client_secrets.json", FileMode.Open,
FileAccess.Read))
{
GoogleWebAuthorizationBroker.Folder = "Tasks.Auth.Store";
StoredCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { DriveService.Scope.Drive,
DriveService.Scope.DriveFile },
"user",
CancellationToken.None,
new SavedDataStore(myStoredResponse)).Result;
}
.
해당 튜토리얼에 첨부 된 샘플 프로젝트가 있습니다.
을 사용하여 새로 토큰:
var init = new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = "OAuth_Client_ID_From_GoogleAPI",
ClientSecret = "OAuth_Client_Secret"
},
Scopes = new string[] {"MY_SCOPES"}
};
var token = new TokenResponse { RefreshToken = "MY_REFRESH_TOKEN" };
var credential = new UserCredential(new Google.Apis.Auth.OAuth2.Flows.AuthorizationCodeFlow(init), "", token);
//init your Google API service, in this example Google Directory
var service = new DirectoryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "",
});
무엇이 없다면 새로 토큰?가장 쉬운 지시를 따르는 것은 Google 에서 SDK docs.첫째
다운로드 자격 증명서 Google API 프로젝트입니다.파일의 이름을 credentials.json
.다음 코드를 실행:
using (var stream =
new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
// The file token.json stores the user's access and refresh tokens, and is created
// automatically when the authorization flow completes for the first time.
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
이 폴더를 만듭니다.json 와 폴더 내부에 또 다른 json 있는 파일의 refresh_token.
{
"access_token" : "asdf",
"token_type" : "Bearer",
"expires_in" : 3600,
"refresh_token" : "XXX",
"scope" : "https://www.googleapis.com/auth/admin.directory.user.readonly",
"Issued" : "2019-02-08T12:37:06.157-08:00",
"IssuedUtc" : "2019-02-08T20:37:06.157Z"
}
내가 선호하는 사용하지 않 GoogleWebAuthorizationBroker 기 때문에 그것은 자동차를 시작할 때 웹 브라우저
토큰을 발견되지 않습니다.내가 선호하는 오래된 학교법의 새로 토큰하여 액세스 코드를 받으시기 바랍니다.이것은 매우 비슷를 사용하여 Google OAuthUtil.CreateOAuth2AuthorizationUrl
고 OAuthUtil.GetAccessToken
구글에서 기존의 OAuth API 를 사용합니다.
var a = new Google.Apis.Auth.OAuth2.Flows.GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = "asdf",
ClientSecret = "hij"
},
Scopes = Scopes
};
var flow = new Google.Apis.Auth.OAuth2.Flows.AuthorizationCodeFlow(a);
var url = flow.CreateAuthorizationCodeRequest(GoogleAuthConsts.InstalledAppRedirectUri).Build().AbsoluteUri;
Console.WriteLine("Go to this URL and get access code: " + url);
Console.Write("Enter access code: ");
var code = Console.ReadLine();
Console.WriteLine("Fetching token for code: _" + code + "_");
var r = flow.ExchangeCodeForTokenAsync("user", code, GoogleAuthConsts.InstalledAppRedirectUri, CancellationToken.None).Result;
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(r));