问题描述
我已经在URL documentation中创建了一个应用程序(选择“凭据”->“创建凭据”->“ OAuth客户端ID”),并指定了重定向URL。 =>我得到了client_id和client_secret,然后使用这些client_id和client_secret编写了一个小型springboot应用程序。
=>运行该项目,并将其重定向到我配置的URL(localhost:8080 / googleOauth / user)。 =>我在我的控制器中获得了带有accesstokenValue的Principal对象,通过使用此accesstoken,我试图调用日历api以获取事件列表但出错了
代码:
@RequestMapping(value = "/user")
public Principal user(Principal principal) {
System.out.println("*******************************principal *\n " + principal);
System.out.println(principal.getName());
if (principal != null) {
OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) principal;
OAuth2AuthenticationDetails oauthDetls = ((OAuth2AuthenticationDetails) oAuth2Authentication.getDetails());
System.out.println("Bearer Token => "+oauthDetls.getTokenType()+" "+oauthDetls.getTokenValue());
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
GoogleCredential credentials = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setClientSecrets("1048632525615-ib80u833vjpou4dglknsa007kpo4gbqs.apps.googleusercontent.com","ZH0ln3VtYNISWBiSZrOmd21u")
.build();
credentials.setAccesstoken(oauthDetls.getTokenValue());
Calendar service = new Calendar.Builder(GoogleNetHttpTransport.newTrustedTransport(),new JacksonFactory(),credentials)
.build();
// Retrieve an event
Events event = service.events().list("primary").execute();
System.out.println("Events Summary => "+event.getSummary());
}
return principal;
}
错误:
{
"error":{
"code":403,"message":"Request had insufficient authentication scopes.","errors":[
{
"message":"Insufficient Permission","domain":"global","reason":"insufficientPermissions"
}
],"status":"PERMISSION_DENIED"
}
}
请指导我哪里错了。
解决方法
我的建议是您经历Calendar API java quickstart。您正处于正确的轨道,因为您确实需要凭据。但是,您缺少授权过程中的重要部分,这些部分是您要访问的作用域,并且还必须为创建凭据的项目启用这些作用域。