OAuth Login Solution(1)Java Codes

OAuthLoginSolution(1)JavaCodes

1ImplementationinJava

SomeDependenciesinbuild.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'

ClassGeneratetheAuthURLinOauthGmailApp.java

packagecom.sillycat.gmailapi;

importjava.util.Arrays;

importcom.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;

importcom.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;

importcom.google.api.client.http.HttpTransport;

importcom.google.api.client.http.javanet.NetHttpTransport;

importcom.google.api.client.json.JsonFactory;

importcom.google.api.client.json.jackson2.JacksonFactory;

importcom.google.api.services.gmail.GmailScopes;

publicclassOauthGmailApp{

privatestaticfinalStringCLIENT_id="43144392xxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com";

privatestaticfinalStringCLIENT_SECRET=“xxxxxxxxxxxxxxx";

privatestaticfinalStringCALLBACK_URI="http://requestb.in/xxxxxxx";

privatestaticfinalStringUSER_INFO_URL="https://www.googleapis.com/auth/userinfo.profile";

privatestaticfinalStringEMAIL_INFO_URL="https://www.googleapis.com/auth/userinfo.email";

privatestaticfinalJsonFactoryJSON_FACTORY=newJacksonFactory();

privatestaticfinalHttpTransportHTTP_TRANSPORT=newNetHttpTransport();

//Arrays.asList(GmailScopes.GMAIL_READONLY)

//GmailScopes.all()

publicstaticvoidmain(String[]args){

GoogleAuthorizationCodeFlowflow=newGoogleAuthorizationCodeFlow.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();

GoogleAuthorizationCodeRequestUrlurl=flow.newAuthorizationUrl();

Stringurl_str=url.setRedirectUri(CALLBACK_URI).setState("accountId123").build();

url_str=url_str+"&[email protected]";

System.out.println("URL="+url_str);

}

}

ThisClasswillprintouttheAuthURL,withthisURL,wecanopenachromewindow,putourgmailnameandpasswordtoauthorizethepermission.

GooglewillcallthecallbackURLwithinformationlikethis:

state=accountId123&code=4/TL65z3EXA0Ls6b9pWIaAxxxxxxxxxxxx

ThecodeisanaccessToken,wecanuseitonce.Thestateisjustanidentifierforus.Wepassinthe‘accountId123’,thenwereceive‘accountId123’.

TheclassFetchtheRefreshTokeninOauthGmailTokenFetchApp.java

packagecom.sillycat.gmailapi;

importjava.io.IOException;

importjava.util.Arrays;

importcom.google.api.client.auth.oauth2.Credential;

importcom.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;

importcom.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;

importcom.google.api.client.http.HttpTransport;

importcom.google.api.client.http.javanet.NetHttpTransport;

importcom.google.api.client.json.JsonFactory;

importcom.google.api.client.json.jackson2.JacksonFactory;

importcom.google.api.services.gmail.GmailScopes;

publicclassOauthGmailTokenFetchApp{

privatestaticfinalStringCLIENT_id="431443920320-540ruq1xxxxxxxxxxxxxxxxx.apps.googleusercontent.com";

privatestaticfinalStringCLIENT_SECRET=“xxxxxxxxxxxxxxxx";

privatestaticfinalStringCALLBACK_URI="http://requestb.in/xxxxxxxxx";

privatestaticfinalStringauthCode="4/iXvUVF79HNMhntMqxxxxxxxxxxxxxxxx";

privatestaticfinalJsonFactoryJSON_FACTORY=newJacksonFactory();

privatestaticfinalHttpTransportHTTP_TRANSPORT=newNetHttpTransport();

publicstaticvoidmain(String[]args)throwsIOException{

GoogleAuthorizationCodeFlowflow=newGoogleAuthorizationCodeFlow.Builder(

HTTP_TRANSPORT,JSON_FACTORY,CLIENT_ID,CLIENT_SECRET,

Arrays.asList(GmailScopes.GMAIL_READONLY)).setAccessType("offline").setApprovalPrompt("force").build();

GoogleTokenResponseresponse=flow.newTokenRequest(authCode)

.setRedirectUri(CALLBACK_URI).execute();

System.out.println("RefreshToken="+response.getRefreshToken());

}

}

UsetheAccessTokenwegetfromthestepone,wecanfetchtherefreshtoken,weneedkeepthisrefreshtokensecret,becausethisrefreshtokencanalwaysgettheaccesstoken.

TheClassGenerateanewAccessTokenandFetchUserProfileinOauthGmailFetchInfoApp.java

packagecom.sillycat.gmailapi;

importjava.io.IOException;

importjava.util.Arrays;

importjava.util.List;

importcom.google.api.client.auth.oauth2.Credential;

importcom.google.api.client.auth.oauth2.TokenResponse;

importcom.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;

importcom.google.api.client.http.GenericUrl;

importcom.google.api.client.http.HttpRequest;

importcom.google.api.client.http.HttpRequestFactory;

importcom.google.api.client.http.HttpTransport;

importcom.google.api.client.http.javanet.NetHttpTransport;

importcom.google.api.client.json.JsonFactory;

importcom.google.api.client.json.jackson2.JacksonFactory;

importcom.google.api.services.gmail.Gmail;

importcom.google.api.services.gmail.GmailScopes;

importcom.google.api.services.gmail.model.Label;

importcom.google.api.services.gmail.model.ListLabelsResponse;

publicclassOauthGmailFetchInfoApp{

privatestaticfinalStringCLIENT_ID=“431443920320-xxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com";

privatestaticfinalStringCLIENT_SECRET=“xxxxxxxxxxxxxxxxx";

privatestaticfinalStringREFRESH_TOKEN="1/poLb6SOjE7TRCOdZ9WCX54Qzxxxxxxxxxxxxxxx";

privatestaticfinalStringAPPLICATION_name="GmailAPIJavaQuickstart";

privatestaticfinalStringUSER_INFO_URL="https://www.googleapis.com/auth/userinfo.profile";

privatestaticfinalJsonFactoryJSON_FACTORY=newJacksonFactory();

privatestaticfinalHttpTransportHTTP_TRANSPORT=newNetHttpTransport();

publicstaticvoidmain(String[]args)throwsIOException{

GoogleAuthorizationCodeFlowflow=newGoogleAuthorizationCodeFlow.Builder(

HTTP_TRANSPORT,JSON_FACTORY,CLIENT_ID,CLIENT_SECRET,

Arrays.asList(GmailScopes.GMAIL_READONLY))

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

TokenResponsetokenResponse=newTokenResponse();

tokenResponse.setRefreshToken(REFRESH_TOKEN);

Credentialcredential=flow.createAndStoreCredential(tokenResponse,

null);

//GmailmaiService=newGmail.Builder(HTTP_TRANSPORT,JSON_FACTORY,credential).setApplicationName(APPLICATION_NAME).build();

//

//Stringuser="me";

//ListLabelsResponselistResponse=maiService.users().labels().list(user)

//.execute();

//List<Label>labels=listResponse.getLabels();

//if(labels.size()==0){

//System.out.println("Nolabelsfound.");

//}else{

//System.out.println("Labels:");

//for(Labellabel:labels){

//System.out.printf("-%s\n",label.getName());

//}

//}

finalHttpRequestFactoryrequestFactory=HTTP_TRANSPORT.createRequestFactory(credential);

//Makeanauthenticatedrequest

finalGenericUrlurl=newGenericUrl(USER_INFO_URL);

finalHttpRequestrequest=requestFactory.buildGetRequest(url);

request.getHeaders().setContentType("application/json");

//request.execute().parseAsString();

request.execute();

//System.out.println(newString(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

}

}

OncewegettheaccessToken,wecanvisittheuserprofilefromthelinkattheverybottomlikethis.

https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=ya29.dQJ3ez8z8vMCxin6Rkrb_XFHnOmaums1gsARsMyebDlfPc_losgszmpxZv6_eAiJN8_A

ThereturnvaluewillbeasJSONformatasfollow:

{

"id":“xxxxxxxxxx",

"email":“[email protected]",

"verified_email":true,

"name":“SillycatMobile",

"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

相关推荐