谷歌眼镜Mirror API开发指南之Authorizing Requests

原文地址:http://bbs.seacat.cn/thread-890-1-1.html




授权请求

请求GoogleMirror API授权必须使用OAuth2.0认证.当用户离线时,您应该使用服务器端来代表应用程序需要访问的GoogleAPI。这种方法需要通过从客户端到服务器一次性授权代码,用于获取您服务器的访问和刷新令牌。

创建一个客户端ID和客户端密码

首先,你要为你的应用程序激活Google MirrorAPI.你在可以在谷歌API控制台(Google APIs Console)为你的API项目来激活。

1.     在谷歌API控制台(Google APIsConsole)创建一个项目

2.     在您的API项目选择服务(Services)选项卡,启用Google MirrorAPI

3.     API项目选项卡选择API访问(API Access,并单击创建一个OAuth 2.0客户端IDCreatean OAuth 2.0 client ID

4.     在品牌信息部分(BrandingInformation),为你的应用程序取一个名字,比如(我的眼镜服务),点击下一步(Next),提供一个可选的产品logo

5.     在客户端ID设置部分(Client IDSettings,请执行以下操作

a.    在应用程序类型(Applicationtype)选择Web应用程序(Web application

b.     点击链接标题旁边的更多选项(more options,你的网站或主机名(Your site orhostname

c.     列出你主机名的授权重定向URIAuthorizedRedirect URIs)和JavaScript的源(JavaScriptorigins

d.     点击创建客户端ID(Click CreateClient ID)

6.     API访问(API Access)页面,找到Web应用程序客户端IDClient ID forWeb applications),注意客户端IDClient ID)和客户端密码(ClientSecret)的值

处理授权请求

当用户首次加载应用程序时,会弹出一个对话框,允许您的应用程序来访问他们的谷歌眼镜与请求的权限范围。初始授权后,如果应用程序的客户端ID更改或请求的范围发生了变化用户才会看到允许对话框。


认证用户

这个初始登录后会返回授权结果对象, 如果成功该对象会包含一个授权代码。

访问令牌交换授权代码

授权代码是一次性代码,您的服务器可以换取一个访问令牌。这个访问令牌传递到Google MirrorAPI允许应用程序在有限的时间内访问用户数据。

如果您的应用程序需要离线访问,第一次应用程序交换授权代码,它也收到一个刷新令牌,使用接收到的新的访问令牌后以前的令牌就过期了。您的应用程序要存储这种更新后的令牌。

重要:总是存储用户刷新令牌。如果你的应用需要一个新的刷新令牌必须放松一个参数来批准请求,这时用户就能在你的应用程序中看到一个允许的对话框了

下面的代码示例演示交换授权代码,离线访问一个访问令牌和刷新令牌存储。

client_secrets.json文件替换CLIENTSECRETS_LOCATION 的值



JAVA:


[java] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. import com.google.api.client.auth.oauth2.Credential;  

  2. import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;  

  3. import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;  

  4. import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;  

  5. import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;  

  6. import com.google.api.client.http.HttpTransport;  

  7. import com.google.api.client.http.javanet.NetHttpTransport;  

  8. import com.google.api.client.json.jackson.JacksonFactory;  

  9. import com.google.api.services.oauth2.Oauth2;  

  10. import com.google.api.services.oauth2.model.Userinfo;  

  11. import java.io.IOException;  

  12. import java.util.Arrays;  

  13. import java.util.List;  

  14. // ...

  15. class MyClass {  

  16. // Path to client_secrets.json which should contain a JSON document such as:

  17. //   {

  18. //     "web": {

  19. //       "client_id": "[[YOUR_CLIENT_ID]]",

  20. //       "client_secret": "[[YOUR_CLIENT_SECRET]]",

  21. //       "auth_uri": "https://accounts.google.com/o/oauth2/auth",

  22. //       "token_uri": "https://accounts.google.com/o/oauth2/token"

  23. //     }

  24. //   }

  25. privatestaticfinal String CLIENTSECRETS_LOCATION = "client_secrets.json";  

  26. privatestaticfinal String REDIRECT_URI = "<YOUR_REGISTERED_REDIRECT_URI>";  

  27. privatestaticfinal List<String> SCOPES = Arrays.asList(  

  28. "https://www.googleapis.com/auth/glass.timeline",  

  29. "https://www.googleapis.com/auth/userinfo.profile");  

  30. privatestatic GoogleAuthorizationCodeFlow flow = null;  

  31. /**

  32.   * Exception thrown when an error occurred while retrieving credentials.

  33.   */

  34. publicstaticclass GetCredentialsException extends Exception {  

  35. protected String authorizationUrl;  

  36. /**

  37.     * Construct a GetCredentialsException.

  38.     *

  39.     * @param authorizationUrl The authorization URL to redirect the user to.

  40.     */

  41. public GetCredentialsException(String authorizationUrl) {  

  42. this.authorizationUrl = authorizationUrl;  

  43.    }  

  44. /**

  45.     * Set the authorization URL.

  46.     */

  47. publicvoid setAuthorizationUrl(String authorizationUrl) {  

  48. this.authorizationUrl = authorizationUrl;  

  49.    }  

  50. /**

  51.     * @return the authorizationUrl

  52.     */

  53. public String getAuthorizationUrl() {  

  54. return authorizationUrl;  

  55.    }  

  56.  }  

  57. /**

  58.   * Exception thrown when a code exchange has failed.

  59.   */

  60. publicstaticclass CodeExchangeException extends GetCredentialsException {  

  61. /**

  62.     * Construct a CodeExchangeException.

  63.     *

  64.     * @param authorizationUrl The authorization URL to redirect the user to.

  65.     */

  66. public CodeExchangeException(String authorizationUrl) {  

  67. super(authorizationUrl);  

  68.    }  

  69.  }  

  70. /**

  71.   * Exception thrown when no refresh token has been found.

  72.   */

  73. publicstaticclass NoRefreshTokenException extends GetCredentialsException {  

  74. /**

  75.     * Construct a NoRefreshTokenException.

  76.     *

  77.     * @param authorizationUrl The authorization URL to redirect the user to.

  78.     */

  79. public NoRefreshTokenException(String authorizationUrl) {  

  80. super(authorizationUrl);  

  81.    }  

  82.  }  

  83. /**

  84.   * Exception thrown when no user ID could be retrieved.

  85.   */

  86. privatestaticclass NoUserIdException extends Exception {  

  87.  }  

  88. /**

  89.   * Retrieved stored credentials for the provided user ID.

  90.   *

  91.   * @param userId User's ID.

  92.   * @return Stored Credential if found, {@code null} otherwise.

  93.   */

  94. static Credential getStoredCredentials(String userId) {  

  95. // TODO: Implement this method to work with your database. Instantiate a new

  96. // Credential instance with stored accessToken and refreshToken.

  97. thrownew UnsupportedOperationException();  

  98.  }  

  99. /**

  100.   * Store OAuth 2.0 credentials in the application's database.

  101.   *

  102.   * @param userId User's ID.

  103.   * @param credentials The OAuth 2.0 credentials to store.

  104.   */

  105. staticvoid storeCredentials(String userId, Credential credentials) {  

  106. // TODO: Implement this method to work with your database.

  107. // Store the credentials.getAccessToken() and credentials.getRefreshToken()

  108. // string values in your database.

  109. thrownew UnsupportedOperationException();  

  110.  }  

  111. /**

  112.   * Build an authorization flow and store it as a static class attribute.

  113.   *

  114.   * @return GoogleAuthorizationCodeFlow instance.

  115.   * @throws IOException Unable to load client_secrets.json.

  116.   */

  117. static GoogleAuthorizationCodeFlow getFlow() throws IOException {  

  118. if (flow == null) {  

  119.      HttpTransport httpTransport = new NetHttpTransport();  

  120.      JacksonFactory jsonFactory = new JacksonFactory();  

  121.      GoogleClientSecrets clientSecrets =  

  122.          GoogleClientSecrets.load(jsonFactory,  

  123.              MyClass.class.getResourceAsStream(CLIENTSECRETS_LOCATION));  

  124.      flow =  

  125. new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, clientSecrets, SCOPES)  

  126.              .setAccessType("offline").setApprovalPrompt("force").build();  

  127.    }  

  128. return flow;  

  129.  }  

  130. /**

  131.   * Exchange an authorization code for OAuth 2.0 credentials.

  132.   *

  133.   * @param authorizationCode Authorization code to exchange for OAuth 2.0

  134.   *        credentials.

  135.   * @return OAuth 2.0 credentials.

  136.   * @throws CodeExchangeException An error occurred.

  137.   */

  138. static Credential exchangeCode(String authorizationCode)  

  139. throws CodeExchangeException {  

  140. try {  

  141.      GoogleAuthorizationCodeFlow flow = getFlow();  

  142.      GoogleTokenResponse response =  

  143.          flow.newTokenRequest(authorizationCode).setRedirectUri(REDIRECT_URI).execute();  

  144. return flow.createAndStoreCredential(response, null);  

  145.    } catch (IOException e) {  

  146.      System.err.println("An error occurred: " + e);  

  147. thrownew CodeExchangeException(null);  

  148.    }  

  149.  }  

  150. /**

  151.   * Send a request to the UserInfo API to retrieve the user's information.

  152.   *

  153.   * @param credentials OAuth 2.0 credentials to authorize the request.

  154.   * @return User's information.

  155.   * @throws NoUserIdException An error occurred.

  156.   */

  157. static Userinfo getUserInfo(Credential credentials)  

  158. throws NoUserIdException {  

  159.    Oauth2 userInfoService =  

  160. new Oauth2.Builder(new NetHttpTransport(), new JacksonFactory(), credentials).build();  

  161.    Userinfo userInfo = null;  

  162. try {  

  163.      userInfo = userInfoService.userinfo().get().execute();  

  164.    } catch (IOException e) {  

  165.      System.err.println("An error occurred: " + e);  

  166.    }  

  167. if (userInfo != null && userInfo.getId() != null) {  

  168. return userInfo;  

  169.    } else {  

  170. thrownew NoUserIdException();  

  171.    }  

  172.  }  

  173. /**

  174.   * Retrieve the authorization URL.

  175.   *

  176.   * @param userId User's Google ID.

  177.   * @param state State for the authorization URL.

  178.   * @return Authorization URL to redirect the user to.

  179.   * @throws IOException Unable to load client_secrets.json.

  180.   */

  181. publicstatic String getAuthorizationUrl(String userId, String state) throws IOException {  

  182.    GoogleAuthorizationCodeRequestUrl urlBuilder =  

  183.        getFlow().newAuthorizationUrl().setRedirectUri(REDIRECT_URI).setState(state);  

  184.    urlBuilder.set("user_id", userId);  

  185. return urlBuilder.build();  

  186.  }  

  187. /**

  188.   * Retrieve credentials using the provided authorization code.

  189.   *

  190.   * This function exchanges the authorization code for an access token and

  191.   * queries the UserInfo API to retrieve the user's Google ID. If a

  192.   * refresh token has been retrieved along with an access token, it is stored

  193.   * in the application database using the user's Google ID as key. If no

  194.   * refresh token has been retrieved, the function checks in the application

  195.   * database for one and returns it if found or throws a NoRefreshTokenException

  196.   * with the authorization URL to redirect the user to.

  197.   *

  198.   * @param authorizationCode Authorization code to use to retrieve an access

  199.   *        token.

  200.   * @param state State to set to the authorization URL in case of error.

  201.   * @return OAuth 2.0 credentials instance containing an access and refresh

  202.   *         token.

  203.   * @throws NoRefreshTokenException No refresh token could be retrieved from

  204.   *         the available sources.

  205.   * @throws IOException Unable to load client_secrets.json.

  206.   */

  207. publicstatic Credential getCredentials(String authorizationCode, String state)  

  208. throws CodeExchangeException, NoRefreshTokenException, IOException {  

  209.    String userId = "";  

  210. try {  

  211.      Credential credentials = exchangeCode(authorizationCode);  

  212.      Userinfo userInfo = getUserInfo(credentials);  

  213.      userId = userInfo.getId();  

  214. if (credentials.getRefreshToken() != null) {  

  215.        storeCredentials(userId, credentials);  

  216. return credentials;  

  217.      } else {  

  218.        credentials = getStoredCredentials(userId);  

  219. if (credentials != null && credentials.getRefreshToken() != null) {  

  220. return credentials;  

  221.        }  

  222.      }  

  223.    } catch (CodeExchangeException e) {  

  224.      e.printStackTrace();  

  225. // Glass services should try to retrieve the user and credentials for the current

  226. // session.

  227. // If none is available, redirect the user to the authorization URL.

  228.      e.setAuthorizationUrl(getAuthorizationUrl(userId, state));  

  229. throw e;  

  230.    } catch (NoUserIdException e) {  

  231.      e.printStackTrace();  

  232.    }  

  233. // No refresh token has been retrieved.

  234.    String authorizationUrl = getAuthorizationUrl(userId, state);  

  235. thrownew NoRefreshTokenException(authorizationUrl);  

  236.  }  








你可能感兴趣的:(Google,服务器,谷歌,应用程序,下一步)