Spring Boot社交登录和Google Calendar API [英] Spring Boot Social Login and Google Calendar API

查看:298
本文介绍了Spring Boot社交登录和Google Calendar API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过Spring Security OAuth2重用最终用户Google身份验证以访问Web应用程序中的Google Calendar API

Reuse End-User Google Authentication via Spring Security OAuth2 to access Google Calendar API in Web Application

我能够通过Spring Security登录创建一个小的Spring Boot Web应用程序

I was able to create a small Spring Boot Web application with Login through Spring Security

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/user ,并要求用户提供google登录.成功登录后,配置文件json在浏览器中显示为来自以下位置的响应:

When application starts I can access http://localhost:8080/user and user is asked for google login. After successful login profile json is shown in a browser as the response from:

@RestController
class SecurityController {
    @RequestMapping("/user")
    fun user(principal: Principal): Principal {
        return principal
    }
}

SecurityConfiguration.kt

@Configuration
class SecurityConfiguration : WebSecurityConfigurerAdapter() {
    @Throws(Exception::class)
    override fun configure(http: HttpSecurity) {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .oauth2Login()
    }
}

问题

我想重用此身份验证来检索所有用户的日历事件.以下代码取自Google关于访问日历API的教程,但它创建了一个完全独立的授权流程,并要求用户登录.

Question

I want to reuse this authentication to retrieve all user's Calendar Events. The following code is taken from google's tutorial on accessing calendar API but it creates a completely independent authorization flow and asks user to log in.

    @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帐户上的日历事件?

How can I reuse already done authentication to access end user's calendar events on Google account?

推荐答案

如果我正确理解,您的意思是重用身份验证是您想使用Spring为您检索的访问和刷新令牌,以便将它们用于针对Google API的请求.

If I understand correctly, what you mean be reusing the authentication is that you want to use the access and refresh tokens Spring retrieved for you in order to use them for requests against Google API.

用户身份验证详细信息可以注入到端点方法中,如下所示:

The user authentication details can be injected into an endpoint method like this:

import org.springframework.security.oauth2.client.OAuth2AuthorizedClient
import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController

@RestController
class FooController(val historyService: HistoryService) {

    @GetMapping("/foo")
    fun foo(@RegisteredOAuth2AuthorizedClient("google") user: OAuth2AuthorizedClient) {
        user.accessToken
    }

}

使用OAuth2AuthorizedClient中的详细信息,您应该可以使用Google API进行任何所需的操作.

With the details in OAuth2AuthorizedClient you should be able to do anything you need with the google API.

如果您需要在没有用户请求服务的情况下访问API,则可以将OAuth2AuthorizedClientService注入到托管组件中,并按以下方式使用它:

If you need to access the API without a user making a request to your service, you can inject OAuth2AuthorizedClientService into a managed component, and use it like this:

import org.springframework.security.oauth2.client.OAuth2AuthorizedClient
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService
import org.springframework.stereotype.Service

@Service
class FooService(val clientService: OAuth2AuthorizedClientService) {

    fun foo() {
        val user = clientService.loadAuthorizedClient<OAuth2AuthorizedClient>("google", "principal-name")
        user.accessToken
    }

}

这篇关于Spring Boot社交登录和Google Calendar API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆