Problem
通过 Spring Security OAuth2 重用最终用户 Google 身份验证来访问 Web 应用程序中的 Google Calendar API
描述
我能够通过 Spring Security 登录创建一个小型 Spring Boot Web 应用程序
应用程序.yaml
spring:
security:
oauth2:
client:
registration:
google:
client-id: <id>
client-secret: <secret>
scope:
- email
- profile
- https://www.googleapis.com/auth/calendar.readonly
当应用程序启动时我可以访问http://localhost:8080/用户并要求用户登录谷歌。成功登录后,配置文件 json 将作为以下响应显示在浏览器中:
安全控制器
@RestController
class SecurityController {
@RequestMapping("/user")
fun user(principal: Principal): Principal {
return principal
}
}
安全配置.kt
@Configuration
class SecurityConfiguration : WebSecurityConfigurerAdapter() {
@Throws(Exception::class)
override fun configure(http: HttpSecurity) {
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.oauth2Login()
}
}
Question
我想重用此身份验证来检索所有用户的日历事件。以下代码取自谷歌有关访问日历API的教程,但它创建了一个完全独立的授权流程并要求用户登录。
@Throws(IOException::class)
private fun getCredentials(httpTransport: NetHttpTransport): Credential {
val clientSecrets = loadClientSecrets()
return triggerUserAuthorization(httpTransport, clientSecrets)
}
private fun loadClientSecrets(): GoogleClientSecrets {
val `in` = CalendarQuickstart::class.java.getResourceAsStream(CREDENTIALS_FILE_PATH)
?: throw FileNotFoundException("Resource not found: $CREDENTIALS_FILE_PATH")
return GoogleClientSecrets.load(JSON_FACTORY, InputStreamReader(`in`))
}
private fun triggerUserAuthorization(httpTransport: NetHttpTransport, clientSecrets: GoogleClientSecrets): Credential {
val flow = GoogleAuthorizationCodeFlow.Builder(
httpTransport, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(FileDataStoreFactory(File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.build()
val receiver = LocalServerReceiver.Builder().setPort(8880).build()
return AuthorizationCodeInstalledApp(flow, receiver).authorize("user")
}
如何重复使用已完成的身份验证来访问 Google 帐户上的最终用户日历活动?