双11狂欢大促

盲盒赢 定制羽绒服

开启惊喜盲盒,抽取你的专属好礼

— 惊喜奖品抢先看 —

如何利用Google OAuth2 for Java lib 拿到access token,并用其访问我的网络资源

thinkoversky thinkoversky 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
各位好,

我是一个JAVA新人,最近需要用google 的OAuth2 的java 库做一些事情,不知道如何下手,请指教。

程序要求如下:
用java程序实现一个安全认证,利用google OAuth2 拿到access token并访问受保护资源。

我在网上找到一些资源,写了如下代码。说实话,我不是特别理解这段代码。

首先跳转url如何定?我是打算在web server端实现这段code的,调试时是http:\\localhost,访问的受保护资源是https:\\staging.xxxx.com\v2\application。
其次,如何构造手访问资源的request?网上有一些访问google app的例子,但是不太明白,不知道怎么用。适合我这种要求吗。可否贡献一个这样的例子。

谢谢
	

private static final Collection<String> SCOPE = Arrays.asList("https://www.googleapis.com/auth/urlshortener");
private static final String CALLBACK_URL = "urn:ietf:wg:oauth:2.0:oob";
private static final HttpTransport TRANSPORT = new NetHttpTransport();
private static final JsonFactory JSON_FACTORY = new JacksonFactory();

private static final String CLIENT_ID = "xxxxx"; //use your client ID
private static final String CLIENT_SECRET = "xxxxx"; //use your client secret

GoogleAuthorizationCodeFlow authorizationCodeFlow = new GoogleAuthorizationCodeFlow
.Builder(TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET, SCOPE)
.setCredentialDataStore(new MemoryDataStoreFactory().getDataStore("tokens"))
.build();

String userId = "user-id";
Credential credential = authorizationCodeFlow.loadCredential(userId);
if (credential == null) {
GoogleAuthorizationCodeRequestUrl authorizationUrl = authorizationCodeFlow.newAuthorizationUrl();
authorizationUrl.setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI);
//LOGGER.error("Please, authorize application. Visit {}", authorizationUrl);
Scanner s = new Scanner(System.in);
String code = s.nextLine();
GoogleAuthorizationCodeTokenRequest tokenRequest = authorizationCodeFlow.newTokenRequest(code);
tokenRequest.setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI);
GoogleTokenResponse tokenResponse = tokenRequest.execute();
credential = authorizationCodeFlow.createAndStoreCredential(tokenResponse, userId);
...全文
评论 3
收藏 已收藏
分享
返回顶部
thinkoversky
Web 开发 81,108 成员 341,721 内容