【问题标题】:Google API OAuth 2.0 for Devices Java library适用于设备 Java 库的 Google API OAuth 2.0
【发布时间】:2015-11-22 03:10:43
【问题描述】:

我需要为此处描述的设备实施 OAuth 2.0 流程:

https://developers.google.com/identity/protocols/OAuth2ForDevices

我在 Java 的 Google API 客户端库中找不到任何实现。

例如,支持已安装的应用程序流 (https://developers.google.com/identity/protocols/OAuth2InstalledApp),如下例所示:

https://developers.google.com/api-client-library/java/google-api-java-client/oauth2#installed_applications

但对于没有浏览器的设备则没有...

我应该从头开始实现 API 还是缺少一些东西?

谢谢!

【问题讨论】:

    标签: java google-api google-api-java-client google-oauth


    【解决方案1】:

    我也遇到过同样的问题。我需要弄清楚 api 客户端库的结构。无论如何,这里有一个适用于设备的 oauth 2.0 的示例代码。

    它打印出用户代码和验证网址。转到验证网址并输入用户代码。在您授权应用程序后,它会获得访问和刷新令牌。

    public static class OAuthForDevice{
    
    
        private static final String TOKEN_STORE_USER_ID = "butterflytv";
    
        public static String CLIENT_ID = "Your client id";
        public static String CLIENT_SECRET = "your client secredt";
    
        public static class Device {
            @Key
            public String device_code;
            @Key
            public String user_code;
            @Key
            public String verification_url;
            @Key
            public int expires_in;
            @Key
            public int interval;
        }
    
        public static class DeviceToken {
            @Key
            public String access_token;
            @Key
            public String token_type;
            @Key
            public String refresh_token;
            @Key
            public int expires_in;
        }
    
        public static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
    
        /**
         * Define a global instance of the JSON factory.
         */
        public static final JsonFactory JSON_FACTORY = new JacksonFactory();
    
    
        public static void main(String[] args)  {
            getCredential();
        }
    
        public static Credential getCredential() {
            Credential credential = null;
            try {
                FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File(System.getProperty("user.home")));
                DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore("youtube_token");
    
                credential = loadCredential(TOKEN_STORE_USER_ID, datastore);
                if (credential == null) {
    
                    GenericUrl genericUrl = new GenericUrl("https://accounts.google.com/o/oauth2/device/code");         
    
    
                    Map<String, String> mapData = new HashMap<String, String>();
                    mapData.put("client_id", CLIENT_ID);
                    mapData.put("scope", "https://www.googleapis.com/auth/youtube.upload");
                    UrlEncodedContent content = new UrlEncodedContent(mapData);
                    HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
                        @Override
                        public void initialize(HttpRequest request) {
                            request.setParser(new JsonObjectParser(JSON_FACTORY));
                        }
                    });
                    HttpRequest postRequest = requestFactory.buildPostRequest(genericUrl, content);
    
                    Device device = postRequest.execute().parseAs(Device.class);
                    System.out.println("user code :" + device.user_code);
                    System.out.println("device code :" + device.device_code);
                    System.out.println("expires in:" + device.expires_in);
                    System.out.println("interval :" + device.interval);
                    System.out.println("verification_url :" + device.verification_url);
    
    
                    mapData = new HashMap<String, String>();
                    mapData.put("client_id", CLIENT_ID);
                    mapData.put("client_secret", CLIENT_SECRET);
                    mapData.put("code", device.device_code);
                    mapData.put("grant_type", "http://oauth.net/grant_type/device/1.0");
    
                    content = new UrlEncodedContent(mapData);
                    postRequest = requestFactory.buildPostRequest(new GenericUrl("https://accounts.google.com/o/oauth2/token"), content);
    
                    DeviceToken deviceToken;
                    do {
                        deviceToken = postRequest.execute().parseAs(DeviceToken.class);
    
                        if (deviceToken.access_token != null) {
                            System.out.println("device access token: " + deviceToken.access_token);
                            System.out.println("device token_type: " + deviceToken.token_type);
                            System.out.println("device refresh_token: " + deviceToken.refresh_token);
                            System.out.println("device expires_in: " + deviceToken.expires_in);
                            break;
                        }
                        System.out.println("waiting for " + device.interval + " seconds");
                        Thread.sleep(device.interval * 1000);
    
                    } while (true);
    
    
                    StoredCredential dataCredential = new StoredCredential();
                    dataCredential.setAccessToken(deviceToken.access_token);
                    dataCredential.setRefreshToken(deviceToken.refresh_token);
                    dataCredential.setExpirationTimeMilliseconds((long)deviceToken.expires_in*1000);
    
                    datastore.set(TOKEN_STORE_USER_ID, dataCredential);
    
                    credential = loadCredential(TOKEN_STORE_USER_ID, datastore);
                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }
    
            return credential;
        }
    
        public static Credential loadCredential(String userId, DataStore<StoredCredential> credentialDataStore) throws IOException {
            Credential credential = newCredential(userId, credentialDataStore);
            if (credentialDataStore != null) {
                StoredCredential stored = credentialDataStore.get(userId);
                if (stored == null) {
                    return null;
                }
                credential.setAccessToken(stored.getAccessToken());
                credential.setRefreshToken(stored.getRefreshToken());
                credential.setExpirationTimeMilliseconds(stored.getExpirationTimeMilliseconds());
            } 
            return credential;
        }
    
        private static Credential newCredential(String userId, DataStore<StoredCredential> credentialDataStore) {
    
            Credential.Builder builder = new Credential.Builder(BearerToken
                    .authorizationHeaderAccessMethod()).setTransport(HTTP_TRANSPORT)
                    .setJsonFactory(JSON_FACTORY)
                    .setTokenServerEncodedUrl("https://accounts.google.com/o/oauth2/token")
                    .setClientAuthentication(new ClientParametersAuthentication(CLIENT_ID, CLIENT_SECRET))
                    .setRequestInitializer(null)
                    .setClock(Clock.SYSTEM);
    
            builder.addRefreshListener(
                    new DataStoreCredentialRefreshListener(userId, credentialDataStore));
    
            return builder.build();
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2012-09-19
      • 2018-04-28
      • 1970-01-01
      • 2015-12-09
      • 1970-01-01
      • 1970-01-01
      • 2021-06-10
      • 2018-05-03
      • 2013-05-17
      相关资源
      最近更新 更多