我是谷歌api的新手。我正在使用google.net api,我得到了错误:
访问令牌已过期,无法刷新。错误:刷新错误、刷新错误、更新错误
我可以看到登录屏幕,我接受了权限请求,并且我被正确地重定向到了索引2。当要使用(执行(日历服务时,它会因前面提到的错误而崩溃。
我已经在GOOGLE_AUTH_URL_TEMPLATE变量中将令牌设置为脱机。这应该用于长期代币。
主Auth类
public class TestOAuth2
{
private string applicationName = "g calendar test api";
private string clientId = "---";//From Google Developer console https://console.developers.google.com
private string clientSecret = "---";//From Google Developer console https://console.developers.google.com
private string[] scopes = new string[] {
CalendarService.Scope.Calendar, // Manage your calendars
CalendarService.Scope.CalendarReadonly // View your Calendars
};
private UserCredential userCredential;
string GOOGLE_AUTH_URL_TEMPLATE = "https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&approval_prompt=force&scope={0}&response_type=code&redirect_uri={1}&client_id={2}&login_hint=";
string clientRedirectUri= "http://localhost:57618/Home/Index2";
private CalendarService calendarService;
public TestOAuth2(string access_token)
{
ClientSecrets clientSecrets = new ClientSecrets
{
ClientId = clientId,
ClientSecret = clientSecret
};
GoogleAuthorizationCodeFlow flow = null;
TokenResponse token = new TokenResponse
{
AccessToken = access_token
};
flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = clientSecrets,
Scopes = scopes
});
userCredential = new UserCredential(flow, "user", token);
calendarService = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = userCredential,
ApplicationName = applicationName
});
}
public string GetGoogleOAuthURL()
{
return string.Format(GOOGLE_AUTH_URL_TEMPLATE, String.Join("+", scopes), clientRedirectUri, clientId);
}
private void InitializeCalendarService()
{
calendarService = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = userCredential,
ApplicationName = applicationName
});
}
public string GetEvents()
{
try
{
if (calendarService == null)
{
InitializeCalendarService();
}
var eventRequest = calendarService.Events.List("primary");
eventRequest.TimeMin = DateTime.Now;
eventRequest.ShowDeleted = false;
eventRequest.SingleEvents = true;
eventRequest.MaxResults = 10;
eventRequest.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;
var events = eventRequest.Execute();
string sEvents = "";
foreach (var evt in events.Items)
{
sEvents += evt.Description + "n<br>";
}
return sEvents;
}
catch (Exception ex)
{
return ex.Message;
}
}
}
家庭控制器
public class HomeController : Controller
{
private TestOAuth2 Google;
public string GetGoogleOauthUrl()
{
string temp = "";
try
{
Google = new TestOAuth2(string.Empty);
temp = Google.GetGoogleOAuthURL();
}
catch (Exception ex)
{
temp = ex.Message;
}
return temp;
}
public string GetEvents()
{
string access_token = Request.Headers.Get("access_token");
string temp = "";
try
{
Google = new TestOAuth2(access_token);
temp = Google.GetEvents();
}
catch (Exception ex)
{
temp = ex.Message;
}
return temp;
}
public ActionResult Index()
{
return View();
}
public ActionResult Index2()
{
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
索引视图
<html>
<body>
<script>
document.addEventListener('DOMContentLoaded', function (event) {
fetch("http://localhost:57618/Home/GetGoogleOauthUrl", {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
if (response.ok) {
response.text().then(myAnswer => {
console.log(myAnswer);
window.open(myAnswer, '_blank');
})
} else {
console.error.log("HTTP-Error: " + response.status);
}
});
});
</script>
Hello! Wait For A New Window!
</body>
</html>
索引2查看
<html>
<body>
<script>
function getUrlParameter(name) {
name = name.replace(/[[]/, '\[').replace(/[]]/, '\]');
var regex = new RegExp('[\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/+/g, ' '));
};
document.addEventListener('DOMContentLoaded', function (event) {
let token = getUrlParameter("code");
fetch("http://localhost:57618/Home/GetEvents", {
method: 'GET',
headers: {
'Content-Type': 'application/json',
"access_token": token
}
})
.then(response => {
if (response.ok) {
response.text().then(myAnswer => {
console.log(myAnswer);
document.write("<br><br><br>");
document.write(myAnswer);
})
} else {
console.error.log("HTTP-Error: " + response.status);
}
});
});
</script>
</body>
</html>
我相信您想要使用的是一个不需要刷新的特殊令牌。要做到这一点,您需要在GCP中创建一个项目,然后创建一个服务帐户,并在创建的新服务帐户中下载json密钥。在新创建的项目中启用日历API,并复制服务帐户的电子邮件。转到您想要访问api的日历,并添加您从服务帐户复制的电子邮件。现在,您可以使用服务帐户json密钥进行身份验证,它不会过期。