-
Notifications
You must be signed in to change notification settings - Fork 15
/
OAuth.java
349 lines (310 loc) · 12.1 KB
/
OAuth.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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
/**
* EVE Swagger Interface
* An OpenAPI for EVE Online
*/
package net.troja.eve.esi.auth;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.net.ssl.HttpsURLConnection;
import net.troja.eve.esi.ApiException;
import net.troja.eve.esi.Pair;
public class OAuth implements Authentication {
private static final String URI_OAUTH = "https://login.eveonline.com/v2/oauth";
private static final String URI_AUTHENTICATION = URI_OAUTH + "/authorize";
private static final String URI_ACCESS_TOKEN = URI_OAUTH + "/token";
private static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-._~";
private static final SecureRandom RND = new SecureRandom();
private static final int LEN = 128;
private String refreshToken;
private String clientId;
private String codeVerifier;
private static final Map<String, AccessTokenData> ACCESS_TOKEN_CACHE = new ConcurrentHashMap<>();
@Override
public void applyToParams(final List<Pair> queryParams, final Map<String, String> headerParams) {
// Add auth
AccessTokenData accessTokenData = getAccessTokenData();
if (accessTokenData != null) {
headerParams.put("Authorization", "Bearer " + accessTokenData.getAccessToken());
}
}
public void setAccessToken(final String accessToken) {
ACCESS_TOKEN_CACHE.put(getAuthKey(), new AccessTokenData(accessToken, 0));
}
public void setRefreshToken(final String refreshToken) {
this.refreshToken = refreshToken;
}
public void setClientId(final String clientId) {
this.clientId = clientId;
}
public String getRefreshToken() {
return refreshToken;
}
public String getClientId() {
return clientId;
}
public String getAccessToken() {
AccessTokenData accessTokenData = getAccessTokenData();
if (accessTokenData != null) {
return accessTokenData.getAccessToken();
} else {
return null;
}
}
/**
* Get JWT (JSON Web Token) WARNING: The JWT is unverified. Verifying the
* JWT is beyond the scope of this library. As ESI will verify the token
* when used. See the SSO documentation for JWT Token validation for
* details:
* https://github.com/ccpgames/eveonline-third-party-documentation/blob
* /master/docs/sso/jwt-validation.md
*
* @return Unverified JWT or null
*/
public JWT getJWT() {
AccessTokenData accessTokenData = getAccessTokenData(); // Update access
// token if
// needed;
if (accessTokenData == null) {
return null;
}
try {
String accessToken = accessTokenData.getAccessToken();
String[] parts = accessToken.split("\\.");
if (parts.length != 3) {
return null;
}
ObjectMapper objectMapper = new ObjectMapper();
JWT.Header header = objectMapper.readValue(new String(Base64.getUrlDecoder().decode(parts[0])),
JWT.Header.class);
JWT.Payload payload = objectMapper.readValue(new String(Base64.getUrlDecoder().decode(parts[1])),
JWT.Payload.class);
String signature = parts[2];
return new JWT(header, payload, signature);
} catch (IOException ex) {
return null;
}
}
private AccessTokenData getAccessTokenData() {
// Check if we need a new access token
synchronized (OAuth.class) { // This block is synchronized across all
// threads - so we don't update the access
// token more than once
AccessTokenData accessTokenData = ACCESS_TOKEN_CACHE.get(getAuthKey());
if (refreshToken != null
&& (accessTokenData == null || accessTokenData.getValidUntil() < System.currentTimeMillis())) {
try {
refreshToken();
} catch (final ApiException ex) {
// This error will be handled by ESI once the request is
// made
}
}
}
return ACCESS_TOKEN_CACHE.get(getAuthKey());
}
/**
* Get the authorization uri, where the user logs in.
*
* @param redirectUri
* Uri the user is redirected to, after successful authorization.
* This must be the same as specified at the Eve Online developer
* page.
* @param scopes
* Scopes of the Eve Online SSO.
* @param state
* This should be some secret to prevent XRSF, please read:
* http://www.thread-safe.com/2014/05/the-correct-use-of-state-
* parameter-in.html
* @return
*/
public String getAuthorizationUri(final String redirectUri, final Set<String> scopes, final String state) {
StringBuilder builder = new StringBuilder();
builder.append(URI_AUTHENTICATION);
builder.append("?");
builder.append("response_type=");
builder.append(encode("code"));
builder.append("&redirect_uri=");
builder.append(encode(redirectUri));
builder.append("&client_id=");
builder.append(encode(clientId));
builder.append("&scope=");
builder.append(encode(getScopesString(scopes)));
builder.append("&state=");
builder.append(encode(state));
builder.append("&code_challenge");
builder.append(getCodeChallenge()); // Already url encoded
builder.append("&code_challenge_method=");
builder.append(encode("S256"));
return builder.toString();
}
/**
* Finish the oauth flow after the user was redirected back.
*
* @param code
* Code returned by the Eve Online SSO
* @param state
* This should be some secret to prevent XRSF see
* getAuthorizationUri
* @throws net.troja.eve.esi.ApiException
*/
public void finishFlow(final String code, final String state) throws ApiException {
StringBuilder builder = new StringBuilder();
builder.append("grant_type=");
builder.append(encode("authorization_code"));
builder.append("&client_id=");
builder.append(encode(clientId));
builder.append("&code=");
builder.append(encode(code));
builder.append("&code_verifier=");
builder.append(encode(codeVerifier));
update(builder.toString());
}
private void refreshToken() throws ApiException {
StringBuilder builder = new StringBuilder();
builder.append("grant_type=");
builder.append(encode("refresh_token"));
builder.append("&client_id=");
builder.append(encode(clientId));
builder.append("&refresh_token=");
builder.append(encode(refreshToken));
update(builder.toString());
}
private void update(String urlParameters) throws ApiException {
try {
URL obj = new URL(URI_ACCESS_TOKEN);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
// add request header
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Host", "login.eveonline.com");
// Send post request
con.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.writeBytes(urlParameters);
wr.flush();
}
StringBuilder response;
try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
String inputLine;
response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}
// read json
ObjectMapper objectMapper = new ObjectMapper();
Result result = objectMapper.readValue(response.toString(), Result.class);
// set data
refreshToken = result.getRefreshToken();
String accessToken = result.getAccessToken();
long validUntil = System.currentTimeMillis() + result.getExpiresIn() * 1000 - 5000;
ACCESS_TOKEN_CACHE.put(getAuthKey(), new AccessTokenData(accessToken, validUntil));
} catch (MalformedURLException ex) {
throw new ApiException(ex);
} catch (IOException ex) {
throw new ApiException(ex);
}
}
private String getScopesString(final Set<String> scopes) {
final StringBuilder scopesString = new StringBuilder();
if (scopes != null) {
for (final String scope : scopes) {
if (scopesString.length() > 0) {
scopesString.append(' ');
}
scopesString.append(scope);
}
}
return scopesString.toString();
}
private String getAuthKey() {
return clientId + refreshToken;
}
private static class AccessTokenData {
private final String accessToken;
private final long validUntil;
public AccessTokenData(final String accessToken, final long validUntil) {
this.accessToken = accessToken;
this.validUntil = validUntil;
}
public String getAccessToken() {
return accessToken;
}
public long getValidUntil() {
return validUntil;
}
}
private String getCodeChallenge() {
try {
StringBuilder sb = new StringBuilder(LEN);
for (int i = 0; i < LEN; i++) {
sb.append(AB.charAt(RND.nextInt(AB.length())));
}
codeVerifier = sb.toString();
byte[] ascii = codeVerifier.getBytes(StandardCharsets.US_ASCII);
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] sha = digest.digest(ascii);
return Base64.getUrlEncoder().encodeToString(sha);
} catch (NoSuchAlgorithmException ex) {
return null;
}
}
private String encode(String parameter) {
try {
return URLEncoder.encode(parameter, "UTF-8");
} catch (UnsupportedEncodingException ex) {
return null;
}
}
private static class Result {
@JsonProperty("access_token")
private String accessToken;
@JsonProperty("expires_in")
private Long expiresIn;
@JsonProperty("token_type")
private String tokenType;
@JsonProperty("refresh_token")
private String refreshToken;
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public Long getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(Long expiresIn) {
this.expiresIn = expiresIn;
}
public String getTokenType() {
return tokenType;
}
public void setTokenType(String tokenType) {
this.tokenType = tokenType;
}
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
}
}