Created
November 22, 2019 18:39
-
-
Save pshirshov/e7e3b76168d8d91f2e2afed359901bdc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class GoogleClient() { | |
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest | |
import com.google.api.client.http.javanet.NetHttpTransport | |
import com.google.api.client.json.jackson2.JacksonFactory | |
import com.google.api.services.oauth2.Oauth2 | |
import com.google.auth.http.HttpCredentialsAdapter | |
import com.google.auth.oauth2.{AccessToken, UserCredentials} | |
import scala.jdk.CollectionConverters._ | |
// shared data | |
val scopes =List( | |
"https://www.googleapis.com/auth/userinfo.email", | |
"https://www.googleapis.com/auth/userinfo.profile", | |
) | |
val clientid = "11111-blahblah.apps.googleusercontent.com" | |
// client side | |
val redir = "http://localhost:8080" | |
val oauthUrl = s"https://accounts.google.com/o/oauth2/auth?scope=${scopes.mkString(" ")}&response_type=code&access_type=offline&client_id=${clientid}&redirect_uri=${redir}" | |
val clientCode = java.net.URLDecoder.decode("4...hKuI", "UTF-8") | |
// server side | |
val clientsecret = "PYbo...sCPD" | |
val tokenUri = new URI("https://oauth2.googleapis.com/token") | |
val appName = "MyApp" | |
private val transport = new NetHttpTransport() | |
private val factory = new JacksonFactory() | |
val tokenRes = new GoogleAuthorizationCodeTokenRequest( | |
transport, | |
factory, | |
clientid, | |
clientsecret, | |
clientCode, | |
"http://localhost:8080" | |
).setScopes(scopes.asJava) | |
.execute(); | |
val at = tokenRes.getAccessToken | |
val rt = tokenRes.getRefreshToken | |
println(s"at=$at, rt=$rt") | |
val creds = UserCredentials.newBuilder() | |
.setAccessToken(new AccessToken(at, null)) | |
.setRefreshToken(rt) | |
.setClientId(clientid) | |
.setClientSecret(clientsecret) | |
.setTokenServerUri(tokenUri) | |
.build() | |
// creds.refresh() | |
val initializer = new HttpCredentialsAdapter(creds) | |
val oauth2 = new Oauth2.Builder(transport, factory, initializer) | |
.setApplicationName(appName) | |
.build(); | |
println(oauth2.userinfo().get().execute()) | |
println(oauth2.userinfo().v2().me().get().execute()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment