OAuth2Api 是 Java类
代码:
public class OAuth2Api {
private static final Logger logger = LoggerFactory.getLogger(OAuth2Api.class);
public static final String CRED_SEPERATOR = ":";
private static Map appAccessTokenMap = new ConcurrentHashMap();
public OAuth2Api() {
}
public OAuthResponse getApplicationToken(Environment environment, List scopes) throws IOException {
OAuth2Api.TimedCacheValue appAccessToken = (OAuth2Api.TimedCacheValue)appAccessTokenMap.get(environment);
if (appAccessToken != null && appAccessToken.getValue() != null) {
logger.debug("application access token returned from cache");
return appAccessToken.getValue();
} else {
OkHttpClient client = new OkHttpClient();
String scope = (String) OAuth2Util.buildScopeForRequest(scopes).orElse("");
CredentialUtil.Credentials credentials = CredentialUtil.getCredentials(environment);
String requestData = String.format("grant_type=client_credentials&scope=%s", scope);
RequestBody requestBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), requestData);
Request request = (new Request.Builder()).url(environment.getApiEndpoint()).header("Authorization", this.buildAuthorization(credentials)).header("Content-Type", "application/x-www-form-urlencoded").post(requestBody).build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
logger.debug("Network call to generate new token is successfull");
OAuthResponse oAuthResponse = OAuth2Util.parseApplicationToken(response.body().string());
AccessToken accessToken = (AccessToken)oAuthResponse.getAccessToken().get();
appAccessToken = new OAuth2Api.TimedCacheValue(oAuthResponse, new DateTime(accessToken.getExpiresOn()));
appAccessTokenMap.put(environment, appAccessToken);
return oAuthResponse;
} else {
return OAuth2Util.handleError(response);
}
}
}
private String buildAuthorization(CredentialUtil.Credentials credentials) {
StringBuilder sb = new StringBuilder();
sb.append(credentials.get(CredentialUtil.CredentialType.APP_ID)).append(":").append(credentials.get(CredentialUtil.CredentialType.CERT_ID));
byte[] encodeBytes = Base64.getEncoder().encode(sb.toString().getBytes());
return "Basic " + new String(encodeBytes);
}
public String generateUserAuthorizationUrl(Environment environment, List scopes, Optional state) {
StringBuilder sb = new StringBuilder();
CredentialUtil.Credentials credentials = CredentialUtil.getCredentials(environment);
String scope = (String)OAuth2Util.buildScopeForRequest(scopes).orElse("");
sb.append(environment.getWebEndpoint()).append("?");
sb.append("client_id=").append(credentials.get(CredentialUtil.CredentialType.APP_ID)).append("&");
sb.append("response_type=code").append("&");
sb.append("redirect_uri=").append(credentials.get(CredentialUtil.CredentialType.REDIRECT_URI)).append("&");
sb.append("scope=").append(scope).append("&");
if (state.isPresent()) {
sb.append("state=").append((String)state.get());
}
logger.debug("authorize_url=" + sb.toString());
return sb.toString();
}