`
sillycat
  • 浏览: 2487936 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

OAuth Login Solution(1)Java Codes

 
阅读更多
OAuth Login Solution(1)Java Codes

1 Implementation in Java
Some Dependencies in build.gradle
    compile 'com.google.api-client:google-api-client:1.20.0'
    compile 'com.google.oauth-client:google-oauth-client-jetty:1.20.0'
    compile 'com.google.apis:google-api-services-gmail:v1-rev29-1.20.0'

Class Generate the Auth URL in OauthGmailApp.java
package com.sillycat.gmailapi;

import java.util.Arrays;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.gmail.GmailScopes;

public class OauthGmailApp {
    private static final String CLIENT_ID = "43144392xxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com";
    private static final String CLIENT_SECRET = “xxxxxxxxxxxxxxx";
    private static final String CALLBACK_URI = "http://requestb.in/xxxxxxx";
    private static final String USER_INFO_URL = "https://www.googleapis.com/auth/userinfo.profile";
    private static final String EMAIL_INFO_URL = "https://www.googleapis.com/auth/userinfo.email";
    private static final JsonFactory JSON_FACTORY = new JacksonFactory();
    private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
    //Arrays.asList(GmailScopes.GMAIL_READONLY)
    //GmailScopes.all()
    public static void main(String[] args) {
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                HTTP_TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET,
                Arrays.asList(GmailScopes.MAIL_GOOGLE_COM, GmailScopes.GMAIL_READONLY, USER_INFO_URL, EMAIL_INFO_URL))
        .setAccessType("offline")
        .setApprovalPrompt("force")
        .build();
        GoogleAuthorizationCodeRequestUrl url = flow.newAuthorizationUrl();
        String url_str =  url.setRedirectUri(CALLBACK_URI).setState("accountId123").build();
        url_str = url_str + "&login_hint=luohuazju@gmail.com";
        System.out.println("URL = " + url_str );
    }
}

This Class will print out the Auth URL, with this URL, we can open a chrome window, put our gmail name and password to authorize the permission.
Google will call the callback URL with information like this:
state=accountId123&code=4/TL65z3EXA0Ls6b9pWIaAxxxxxxxxxxxx

The code is an accessToken, we can use it once. The state is just an identifier for us. We pass in the ‘accountId123’, then we receive ‘accountId123’.

The class Fetch the RefreshToken in OauthGmailTokenFetchApp.java
package com.sillycat.gmailapi;

import java.io.IOException;
import java.util.Arrays;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.gmail.GmailScopes;

public class OauthGmailTokenFetchApp {

    private static final String CLIENT_ID = "431443920320-540ruq1xxxxxxxxxxxxxxxxx.apps.googleusercontent.com";

    private static final String CLIENT_SECRET = “xxxxxxxxxxxxxxxx";

    private static final String CALLBACK_URI = "http://requestb.in/xxxxxxxxx";

    private static final String authCode = "4/iXvUVF79HNMhntMqxxxxxxxxxxxxxxxx";

    private static final JsonFactory JSON_FACTORY = new JacksonFactory();
    private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

    public static void main(String[] args) throws IOException {
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                HTTP_TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET,
                Arrays.asList(GmailScopes.GMAIL_READONLY)).setAccessType("offline").setApprovalPrompt("force").build();
        GoogleTokenResponse response = flow.newTokenRequest(authCode)
                .setRedirectUri(CALLBACK_URI).execute();
        System.out.println("Refresh Token = " + response.getRefreshToken());
    }
}

Use the AccessToken we get from the step one, we can fetch the refresh token, we need keep this refresh token secret, because this refresh token can always get the access token.

The Class Generate a new AccessToken and Fetch User Profile in OauthGmailFetchInfoApp.java
package com.sillycat.gmailapi;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.auth.oauth2.TokenResponse;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.gmail.model.Label;
import com.google.api.services.gmail.model.ListLabelsResponse;

public class OauthGmailFetchInfoApp {

    private static final String CLIENT_ID = “431443920320-xxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com";

    private static final String CLIENT_SECRET = “xxxxxxxxxxxxxxxxx";

    private static final String REFRESH_TOKEN = "1/poLb6SOjE7TRCOdZ9WCX54Qzxxxxxxxxxxxxxxx";

    private static final String APPLICATION_NAME = "Gmail API Java Quickstart";

    private static final String USER_INFO_URL = "https://www.googleapis.com/auth/userinfo.profile";

    private static final JsonFactory JSON_FACTORY = new JacksonFactory();
    private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

    public static void main(String[] args) throws IOException {

        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                HTTP_TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET,
                Arrays.asList(GmailScopes.GMAIL_READONLY))
                .setAccessType("offline").setApprovalPrompt("force").build();

        TokenResponse tokenResponse = new TokenResponse();
        tokenResponse.setRefreshToken(REFRESH_TOKEN);

        Credential credential = flow.createAndStoreCredential(tokenResponse,
                null);

//        Gmail maiService = new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();
//
//        String user = "me";
//        ListLabelsResponse listResponse = maiService.users().labels().list(user)
//                .execute();
//        List<Label> labels = listResponse.getLabels();
//        if (labels.size() == 0) {
//            System.out.println("No labels found.");
//        } else {
//            System.out.println("Labels:");
//            for (Label label : labels) {
//                System.out.printf("- %s\n", label.getName());
//            }
//        }

        final HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(credential);
        // Make an authenticated request
        final GenericUrl url = new GenericUrl(USER_INFO_URL);
        final HttpRequest request = requestFactory.buildGetRequest(url);
        request.getHeaders().setContentType("application/json");
        //request.execute().parseAsString();
        request.execute();

        //System.out.println(new String(jsonIdentity.getBytes()));

        System.out.println("accesstoken = " + credential.getAccessToken());
        //https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=ya29.dQJ3ez8z8vMCxin6Rkrb_XFHnOmaums1gsARsMyebDlfPc_losgszmpxZv6_eAiJN8_A
    }

}

Once we get the accessToken, we can visit the user profile from the link at the very bottom like this.
https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=ya29.dQJ3ez8z8vMCxin6Rkrb_XFHnOmaums1gsARsMyebDlfPc_losgszmpxZv6_eAiJN8_A

The return value will be as JSON format as follow:
    {
      "id": “xxxxxxxxxx",
      "email": “luohuazju@gmail.com",
      "verified_email": true,
      "name": “Sillycat Mobile",
      "given_name": “Sillycat",
      "family_name": "Mobile",
      "picture": "https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg",
      "locale": "en",
      "hd": “gmail.com"
    }

References:
https://console.developers.google.com
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics