用于设备Java库的Google API OAuth 2.0

用于设备Java库的Google API OAuth 2.0,java,google-api,google-api-java-client,google-oauth,Java,Google Api,Google Api Java Client,Google Oauth,我需要为下面描述的设备实现OAuth 2.0流程: 我在Google API Java客户端库中找不到这方面的任何实现 例如,支持已安装的应用程序流(),如本例所示: 但是对于没有浏览器的设备没有任何功能 我应该从头开始实现API还是缺少一些东西 谢谢 我也面临同样的问题。我需要弄清楚api客户端库的结构。无论如何,下面是oauth 2.0设备的示例代码 它打印出用户代码和验证url。转到验证url并输入用户代码。在您对应用程序进行身份验证后,它将获得访问和刷新令牌 public stati

我需要为下面描述的设备实现OAuth 2.0流程:

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

例如,支持已安装的应用程序流(),如本例所示:

但是对于没有浏览器的设备没有任何功能

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


谢谢

我也面临同样的问题。我需要弄清楚api客户端库的结构。无论如何,下面是oauth 2.0设备的示例代码

它打印出用户代码和验证url。转到验证url并输入用户代码。在您对应用程序进行身份验证后,它将获得访问和刷新令牌

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();
    }

}
公共静态类OAuthForDevice{
私有静态最终字符串令牌\u存储\u用户\u ID=“butterflytv”;
公共静态字符串CLIENT_ID=“您的客户ID”;
公共静态字符串CLIENT\u SECRET=“您的客户端secredt”;
公共静态类设备{
@钥匙
公共字符串设备_码;
@钥匙
公共字符串用户代码;
@钥匙
公共字符串验证\u url;
@钥匙
公共int-U-in;
@钥匙
公共整数间隔;
}
公共静态类设备停止{
@钥匙
公共字符串访问令牌;
@钥匙
公共字符串令牌类型;
@钥匙
公共字符串刷新\u令牌;
@钥匙
公共int-U-in;
}
公共静态最终HttpTransport HTTP_TRANSPORT=new NetHttpTransport();
/**
*定义JSON工厂的全局实例。
*/
公共静态最终JsonFactory JSON_FACTORY=new JacksonFactory();
公共静态void main(字符串[]args){
getCredential();
}
公共静态凭据getCredential(){
凭证=空;
试一试{
FileDataStoreFactory FileDataStoreFactory=newfiledatastorefactory(新文件(System.getProperty(“user.home”));
DataStore DataStore=fileDataStoreFactory.getDataStore(“youtube_令牌”);
凭证=加载凭证(令牌\存储\用户\ ID,数据存储);
如果(凭证==null){
GenericUrl GenericUrl=新的GenericUrl(“https://accounts.google.com/o/oauth2/device/code");         
Map mapData=new HashMap();
mapData.put(“客户端id”,客户端id);
mapData.put(“范围”https://www.googleapis.com/auth/youtube.upload");
UrlEncodedContent content=新的UrlEncodedContent(mapData);
HttpRequestFactory requestFactory=HTTP_TRANSPORT.createRequestFactory(新的HttpRequestInitializer(){
@凌驾
公共无效初始化(HttpRequest请求){
setParser(新的JsonObjectParser(JSON_工厂));
}
});
HttpRequest postRequest=requestFactory.buildPostRequest(genericUrl,内容);
Device Device=postRequest.execute().parseAs(Device.class);
System.out.println(“用户代码:“+设备.用户代码”);
System.out.println(“设备代码:“+设备.设备代码”);
System.out.println(“expires in:+device.expires\u in”);
System.out.println(“间隔:+设备间隔”);
System.out.println(“验证url:+设备验证url”);
mapData=newhashmap();
mapData.put(“客户端id”,客户端id);
mapData.put(“client\u secret”,client\u secret);
mapData.put(“代码”,设备。设备\代码);
mapData.put(“授权类型”http://oauth.net/grant_type/device/1.0");
内容=新的UrlEncodedContent(mapData);
postRequest=requestFactory.buildPostRequest(新的GenericUrl(“https://accounts.google.com/o/oauth2/token",内容",;
DeviceToken DeviceToken;
做{
deviceToken=postRequest.execute().parseAs(deviceToken.class);
if(deviceToken.access_令牌!=null){
System.out.println(“设备访问令牌:+deviceToken.access_令牌”);
System.out.println(“设备令牌类型:+deviceToken.token\u类型”);
System.out.println(“设备刷新令牌:+deviceToken.refresh\u令牌”);
System.out.println(“设备过期\输入:+deviceToken.expires \输入”);
打破
}
System.out.println(“等待”+设备间隔+“秒”);
线程睡眠(设备间隔*1000);
}虽然(正确);
StoredCredential dataCredential=新的StoredCredential();
dataCredential.setAccessToken(deviceToken.access\u令牌);
dataCredential.setRefreshToken(deviceToken.refresh_令牌);
dataCredential.SetExpirationTimeMillistics((长)deviceToken.expires_in*1000);
datastore.set(令牌\存储\用户\ ID、数据凭证);
凭证=加载凭证(令牌\存储\用户\ ID,数据存储);
}
}
捕获(例外e){
e、 printStackTrace();
}
返回凭证;
}
公共静态凭据加载凭据(字符串userId、数据存储区credentialDataStore)引发IOException{
凭证=新凭证(用户ID、凭证数据库);
if(credentialDataStore!=null){
StoredCredential stored=credentialDataStore.get(userId);
if(存储==null){
返回null;
}
credential.setAccessToken(存储的.getAccessToken());
credential.setRefreshToken(存储的.getRefreshToken());
credential.setExpirationTimeMills(存储的.getExpirationTimeMil