我尝试使用oauth2.0授权使用Google帐户进行身份验证。我成功创建了ClientID和Client Secret。重定向URI是正确的。我用于身份验证的代码是:
@Override
public void filter(HttpServletRequest request, HttpServletResponse response)
throws Exception {
String action = request.getParameter("action");
if ("oauth_callback".equals(action)) {
String providerId = request.getParameter("providerId");
String accountId = request.getParameter("state");
if (this.getAccount().getProvider().getId().equals(providerId)
&& this.getAccount().getId().equals(accountId)) {
String proxyHost = System.getProperty("https.proxyHost");
String proxyPort = System.getProperty("https.proxyPort");
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
proxyHost, Integer.parseInt(proxyPort)));
HttpTransport httpTransport = new NetHttpTransport.Builder()
.setProxy(proxy).build();
JsonFactory jsonFactory = new JacksonFactory();
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, jsonFactory, GoogleDriveUtils.CLIENT_ID,
GoogleDriveUtils.CLIENT_SECRET,
Arrays.asList(DriveScopes.DRIVE))
.setAccessType("online").setApprovalPrompt("auto")
.build();
String codeAttr = request.getParameter("code");
URL serverUrl = new URL(request
.getRequestURL().toString());
String host = serverUrl.getHost();
if (serverUrl.getPort() != -1) {
host += ":" + serverUrl.getPort();
}
String redirectUrl = String.format(
GoogleDriveUtils.REDIRECT_URL, serverUrl.getProtocol(),
host);
GoogleTokenResponse googleResponse = flow
.newTokenRequest(codeAttr).setRedirectUri(redirectUrl)
.execute();
GoogleCredential credential = new GoogleCredential()
.setFromTokenResponse(googleResponse);
// Create a new authorized API client
this.service = new Drive.Builder(httpTransport, jsonFactory,
credential).build();
this.isLoggedIn = true;
logger.debug("Authentication successful.");
initProps();
logger.debug("Account information initialized successfully.");
response.sendRedirect(request.getSession().getServletContext().getContextPath());
}
}
}
执行此代码时:
GoogleTokenResponse googleResponse = flow
.newTokenRequest(codeAttr).setRedirectUri(redirectUrl)
.execute();
google api会返回过期的授权令牌和状态码401.如何解决问题?