在Google开发者控制台中,配置的“重定向URI”必须与使用时C#代码中所提供的“重定向URI”相同。
以下是一个示例,用于从Google Drive API获取access_token:
public class HomeController : Controller
{
private static readonly string CLIENT_ID = "your-client-id";
private static readonly string CLIENT_SECRET = "your-client-secret";
private static readonly string REDIRECT_URI = "your-redirect-uri";
private static readonly string[] SCOPES = { DriveService.Scope.DriveReadonly };
public ActionResult Index()
{
UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
SCOPES,
"user",
CancellationToken.None,
new FileDataStore("Drive.Auth.Store")).Result;
}
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "ASP.NET MVC Google Drive API Sample"
});
// do something with service
return View();
}
public ActionResult Auth()
{
var uri = new Uri(REDIRECT_URI);
var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = CLIENT_ID,
ClientSecret = CLIENT_SECRET
},
Scopes = SCOPES
});
var code = Request.QueryString["code"];
if (code == null)
{
var state = Guid.NewGuid().ToString();
Session["state"] = state;
var authUrl = flow.CreateAuthorizationCodeRequest(uri).Build();
return Redirect(authUrl + "&state=" + state);
}
else
{
var token = flow.ExchangeCodeForTokenAsync("user", code, uri).Result;
Session["access_token"] = token.AccessToken;
Session["refresh_token"] = token.RefreshToken;
return RedirectToAction("Index");
}
}
}
在上述代码示例