-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathAuth.java
199 lines (141 loc) · 7.54 KB
/
Auth.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
package com.socialmedia.google;
/**
* Created by omoto on 24/8/16.
*/
import com.google.api.client.auth.oauth2.*;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.util.Base64;
import com.google.api.client.util.store.DataStore;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.gson.Gson;
import com.socialmedia.SocialMediaConstants;
import com.socialmedia.google.youtube.json.GoogleRequestJSON;
import com.socialmedia.google.youtube.utils.ExtendedAuthorizationCodeInstalledApp;
import java.io.*;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.GeneralSecurityException;
import java.util.List;
/**
* Shared class used by every sample. Contains methods for authorizing a user and caching credentials.
*/
public class Auth implements SocialMediaConstants {
/**
* Define a global instance of the HTTP transport.
*/
public static final String CLIENTID="$YOUR_CLINT_ID";
public static final String CLIENT_SECRET="$YOUR_CLIENT_SECRET";
/**
* Define a global instance of the JSON factory.
*/
/**
* This is the directory that will be used under the user's home directory where OAuth tokens will be stored.
*/
//public static final String REFRESH_TOKEN="REFRESH TOKEN";
LocalServerReceiver localReceiver=null;
/**
* Authorizes the installed application to access user's protected data.
*
* @param scopes list of scopes needed to run youtube upload.
* @param credentialDatastore name of the credential datastore to cache OAuth tokens
*/
public Credential authorize(List<String> scopes, String credentialDatastore,boolean isCallback,String code) throws IOException, URISyntaxException {
String userid="user";
//flag to determine that the request came from the google authentication.
if(isCallback){
System.out.println(credentialDatastore);
byte[] decodedStringByte;
decodedStringByte = Base64.decodeBase64(credentialDatastore);
GoogleRequestJSON requestJSON = new Gson().fromJson(new String(decodedStringByte), GoogleRequestJSON.class);
userid=requestJSON.getUserid();
credentialDatastore=requestJSON.getCredentialDatastore();
}
try {
// Load client secrets.
URI filePath = new URI(GOOGLE_APIKEY);
Reader clientSecretReader = new InputStreamReader(new FileInputStream(filePath.toString()));
//Reader clientSecretReader = new InputStreamReader(Auth.class.getResourceAsStream(GOOGLE_APIKEY));
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, clientSecretReader);
// Checks that the defaults have been replaced (Default = "Enter X here").
if (clientSecrets.getDetails().getClientId().startsWith("Enter") || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
System.out.println(
"Enter Client ID and Secret from https://console.developers.google.com/project/_/apiui/credential "
+ "into src/main/resources/client_secrets.json");
System.exit(1);
}
// This creates the credentials datastore at ~/.oauth-credentials/${credentialDatastore}
FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File(System.getProperty("user.home") + "/" + CREDENTIALS_DIRECTORY));
DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore(credentialDatastore);
//Builds a login URL based on client ID, secret, callback URI, and scopes
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow
.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes)
.setAccessType("offline")
.setApprovalPrompt("auto")
.setCredentialDataStore(datastore)
.build();
InetAddress address = InetAddress.getByName("demo.omoto.io");
System.out.println("address.getName : "+address.getHostName()+" ; address.getCanonicalHostName() : " +address.getCanonicalHostName()+"; address.getHostAddress() : "+address.getHostAddress());
// Build the local server with localhost and any port available.
//used only to pass it in the ExtendedAuthorizationCodeInstalledApp
localReceiver = new LocalServerReceiver.Builder().build();
System.out.println(new LocalServerReceiver.Builder().setHost(address.getHostName()).setPort(8081).getHost());
System.out.println(localReceiver);
Credential credential=null;
ExtendedAuthorizationCodeInstalledApp authorizationCodeInstalledApp=new ExtendedAuthorizationCodeInstalledApp(flow,localReceiver);
//get the credential object from the stored
credential=authorizationCodeInstalledApp.getAuthorizationFromStorage(userid);
//if there is no credentials found ask to authenticate
//this will redirect to the login and will wait till the user login and authorize the app
if(credential==null)
authorizationCodeInstalledApp.getAuthorizationFromGoogle(userid,credentialDatastore);
if(isCallback)
credential=authorizationCodeInstalledApp.saveAuthorizationFromGoogle(userid,credentialDatastore,code);
// Authorize.
//return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user");
return credential;
}catch(Exception e){
e.printStackTrace();
localReceiver.stop();
}finally{
System.out.println("localReceiver shutting down ..");
localReceiver.stop();
}
return null;
}
public Credential generateCredentialWithUserApprovedToken() throws IOException,
GeneralSecurityException,URISyntaxException {
// Load client secrets.
URI filePath = new URI (GOOGLE_APIKEY);
Reader clientSecretReader =new InputStreamReader(new FileInputStream(filePath.toString()));
//Reader clientSecretReader = new InputStreamReader(Auth.class.getResourceAsStream(GOOGLE_APIKEY));
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, clientSecretReader);
return null;
}
/**
*
* @param clientId
* @param clientSecret
* @param jsonFactory
* @param transport
* @param refreshToken
* @return
* @throws IOException
*/
public GoogleCredential getCredentials(String clientId,String clientSecret,JsonFactory jsonFactory,HttpTransport transport,String refreshToken) throws IOException{
GoogleCredential credential = new GoogleCredential.Builder()
.setClientSecrets(clientId, clientSecret)
.setTransport(transport)
.setJsonFactory(jsonFactory)
.build();
credential.setRefreshToken(refreshToken);
// Do a refresh so we can fail early rather than return an unusable credential
credential.refreshToken();
return credential;
}
}