Skip to content

Commit

Permalink
uptaking review comments
Browse files Browse the repository at this point in the history
  • Loading branch information
AsabuHere committed Jun 15, 2024
1 parent 4171512 commit 8716eb1
Show file tree
Hide file tree
Showing 8 changed files with 98 additions and 120 deletions.
10 changes: 7 additions & 3 deletions examples/BearerTokenAuthentication.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
class BearerTokenAuthenticationExamples {
public static void main {
//Getting access token
TokenManager tokenManager = new TokenManagerImpl(GRANT_TYPE, CLIENT_ID, CLIENT_SECRET);
TwilioBearerTokenAuth.init(tokenManager);
//Getting access token - Method #1
TwilioBearerTokenAuth.init(GRANT_TYPE, CLIENT_ID, CLIENT_SECRET);

//Getting access token - Method #2
//To provide custom token manager implementation
//Need not call init method if customer token manager is passed
//TwilioBearerTokenAuth.setTokenManager(new OrgsTokenManager(grantType, clientId, clientSecret));

fetchAccountDetails();
}
Expand Down
30 changes: 24 additions & 6 deletions src/main/java/com/twilio/TwilioBearerTokenAuth.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@
import com.twilio.exception.AuthenticationException;
import com.twilio.http.bearertoken.BearerTokenTwilioRestClient;
import lombok.Getter;
import lombok.Setter;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.twilio.http.bearertoken.TokenManager;
import com.twilio.http.bearertoken.OrgsTokenManager;

@Preview
public class TwilioBearerTokenAuth {
Expand All @@ -18,19 +20,34 @@ public class TwilioBearerTokenAuth {
private static String region = System.getenv("TWILIO_REGION");
private static String edge = System.getenv("TWILIO_EDGE");
private static volatile BearerTokenTwilioRestClient restClient;
@Setter
private static TokenManager tokenManager;

private static volatile ExecutorService executorService;

private TwilioBearerTokenAuth() {
}

public static synchronized void init(final TokenManager tokenManager) {
if (tokenManager == null) {
throw new AuthenticationException("Token Manager cannot be null");
public static synchronized void init(String grantType, String clientId, String clientSecret) {
validateAuthCredentials(grantType, clientId, clientSecret);
tokenManager = new OrgsTokenManager(grantType, clientId, clientSecret);
}
public static synchronized void init(String grantType, String clientId, String clientSecret, String code, String redirectUri, String audience, String refreshToken, String scope) {
validateAuthCredentials(grantType, clientId, clientSecret);
tokenManager = new OrgsTokenManager(grantType, clientId, clientSecret, code, redirectUri, audience, refreshToken, scope);
}

private static void validateAuthCredentials(String grantType, String clientId, String clientSecret){
if (grantType == null) {
throw new AuthenticationException("Grant Type cannot be null");
}
TwilioBearerTokenAuth.tokenManager = tokenManager;
TwilioBearerTokenAuth.accessToken = tokenManager.fetchAccessToken();
if (clientId == null) {
throw new AuthenticationException("Client Id cannot be null");
}
if (clientSecret == null) {
throw new AuthenticationException("Client Secret cannot be null");
}
return;
}

public static BearerTokenTwilioRestClient getRestClient() {
Expand Down Expand Up @@ -61,7 +78,7 @@ public static ExecutorService getExecutorService() {

private static BearerTokenTwilioRestClient buildOAuthRestClient() {

BearerTokenTwilioRestClient.Builder builder = new BearerTokenTwilioRestClient.Builder(accessToken);
BearerTokenTwilioRestClient.Builder builder = new BearerTokenTwilioRestClient.Builder();

if (userAgentExtensions != null) {
builder.userAgentExtensions(TwilioBearerTokenAuth.userAgentExtensions);
Expand All @@ -70,6 +87,7 @@ private static BearerTokenTwilioRestClient buildOAuthRestClient() {
builder.region(TwilioBearerTokenAuth.region);
builder.edge(TwilioBearerTokenAuth.edge);
builder.tokenManager(TwilioBearerTokenAuth.tokenManager);
builder.tokenManager(TwilioBearerTokenAuth.tokenManager);

return builder.build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import com.twilio.http.NetworkHttpClient;
import com.twilio.http.Response;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand Down Expand Up @@ -39,11 +40,11 @@ public class BearerTokenTwilioRestClient {
private final HttpClient httpClient;
@Getter
private final List<String> userAgentExtensions;
private static TokenManager tokenManager;
@Setter
private final TokenManager tokenManager;
private static final Logger logger = LoggerFactory.getLogger(BearerTokenTwilioRestClient.class);

private BearerTokenTwilioRestClient(BearerTokenTwilioRestClient.Builder b) {
this.accessToken = b.accessToken;
this.region = b.region;
this.edge = b.edge;
this.httpClient = b.httpClient;
Expand All @@ -59,15 +60,13 @@ private BearerTokenTwilioRestClient(BearerTokenTwilioRestClient.Builder b) {
}

public static class Builder {
private final String accessToken;
private String region;
private String edge;
private HttpClient httpClient;
private List<String> userAgentExtensions;
private TokenManager tokenManager;

public Builder(String accessToken) {
this.accessToken = accessToken;
public Builder() {
this.region = System.getenv("TWILIO_REGION");
this.edge = System.getenv("TWILIO_EDGE");
userAgentExtensions = new ArrayList<>();
Expand Down Expand Up @@ -108,12 +107,8 @@ public BearerTokenTwilioRestClient build() {
}
}
public Response request(BearerTokenRequest request) {

if (accessToken == null || accessToken.isEmpty()) {
throw new AuthenticationException("Access Token can not be Null or Empty.");
}

if (isAccessTokenExpired()) {
if (accessToken == null || accessToken.isEmpty() || isTokenExpired(this.accessToken)) {
this.accessToken = tokenManager.fetchAccessToken();
}

Expand Down Expand Up @@ -149,8 +144,8 @@ public Response request(BearerTokenRequest request) {
return response;
}

public boolean isAccessTokenExpired() {
DecodedJWT jwt = JWT.decode(this.accessToken);
public boolean isTokenExpired(String token) {
DecodedJWT jwt = JWT.decode(token);
Date expiresAt = jwt.getExpiresAt();
// Add a buffer of 30 seconds
long bufferMilliseconds = 30 * 1000;
Expand Down Expand Up @@ -178,7 +173,6 @@ public void logRequest(final BearerTokenRequest request) {
}
}
}

logger.debug("-- END Twilio API BearerTokenRequest --");
}
}
Expand Down
51 changes: 51 additions & 0 deletions src/main/java/com/twilio/http/bearertoken/OrgsTokenManager.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.twilio.http.bearertoken;

import lombok.Setter;
import com.twilio.exception.ApiException;
import lombok.RequiredArgsConstructor;
import com.twilio.rest.previewiam.organizations.Token;
import com.twilio.rest.previewiam.organizations.TokenCreator;
public class OrgsTokenManager implements TokenManager{

private final String grantType;
private final String clientId;
private final String clientSecret;
private String code;
private String redirectUri;
private String audience;
private String refreshToken;
private String scope;

public OrgsTokenManager(String grantType, String clientId, String clientSecret){
this.grantType = grantType;
this.clientId = clientId;
this.clientSecret = clientSecret;
}

public OrgsTokenManager(String grantType, String clientId, String clientSecret, String code, String redirectUri, String audience, String refreshToken, String scope){
this.grantType = grantType;
this.clientId = clientId;
this.clientSecret = clientSecret;
this.code = code;
this.redirectUri = redirectUri;
this.audience = audience;
this.refreshToken = refreshToken;
this.scope = scope;
}

public synchronized String fetchAccessToken(){
TokenCreator tokenCreator = Token.creator(grantType, clientId).setClientSecret(clientSecret);
if (this.code != null) tokenCreator.setCode(code);
if (this.redirectUri != null) tokenCreator.setRedirectUri(redirectUri);
if (this.audience != null) tokenCreator.setAudience(audience);
if (this.refreshToken != null) tokenCreator.setRefreshToken(refreshToken);
if (this.scope != null) tokenCreator.setScope(scope);
Token token;
try {
token = tokenCreator.create();
} catch(Exception e){
throw new ApiException("Token creation failed");
}
return token.getAccessToken();
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.twilio.http.bearertoken;

public interface TokenManager {
public String refreshAccessToken(String refreshToken);
public String fetchAccessToken();
}
25 changes: 0 additions & 25 deletions src/main/java/com/twilio/http/bearertoken/TokenManagerImpl.java

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -16,64 +16,24 @@

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.twilio.base.Resource;
import com.twilio.converter.Converter;
import com.twilio.converter.Converter;
import java.util.Currency;
import com.twilio.converter.DateConverter;
import com.twilio.converter.Promoter;
import com.twilio.converter.PrefixedCollapsibleMap;
import com.twilio.converter.CurrencyDeserializer;
import com.twilio.base.noauth.Resource;
import com.twilio.exception.ApiConnectionException;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;

import com.twilio.exception.ApiException;
import com.twilio.exception.RestException;
import com.twilio.http.HttpMethod;
import com.twilio.http.Request;
import com.twilio.http.Response;
import com.twilio.http.TwilioRestClient;
import com.twilio.rest.Domains;

import lombok.ToString;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.time.ZonedDateTime;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.util.Map;
import java.time.LocalDate;
import java.math.BigDecimal;
import com.twilio.type.PhoneNumberCapabilities;
import com.twilio.type.FeedbackIssue;
import com.twilio.type.IceServer;
import com.twilio.type.InboundCallPrice;
import com.twilio.type.OutboundPrefixPriceWithOrigin;
import com.twilio.type.OutboundPrefixPrice;
import com.twilio.type.OutboundCallPriceWithOrigin;
import com.twilio.type.PhoneNumberPrice;
import com.twilio.type.InboundSmsPrice;
import com.twilio.type.OutboundSmsPrice;
import com.twilio.type.OutboundCallPrice;
import com.twilio.type.RecordingRule;
import com.twilio.type.SubscribeRule;

@JsonIgnoreProperties(ignoreUnknown = true)
@ToString
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,43 +14,20 @@

package com.twilio.rest.previewiam.organizations;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.twilio.base.Creator;
import com.twilio.http.Request;
import com.twilio.http.TwilioRestClient;
import com.twilio.constant.EnumConstants;
import com.twilio.converter.Promoter;
import com.twilio.exception.ApiConnectionException;
import com.twilio.converter.PrefixedCollapsibleMap;
import com.twilio.converter.Converter;
import com.twilio.exception.ApiException;
import com.twilio.exception.RestException;
import com.twilio.http.HttpMethod;
import com.twilio.http.Response;
import com.twilio.rest.Domains;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.time.LocalDate;
import com.twilio.converter.Converter;
import java.time.ZonedDateTime;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URI;
import java.time.format.DateTimeFormatter;
import com.twilio.converter.DateConverter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

import lombok.ToString;

import java.net.URI;

import com.twilio.base.noauth.Creator;
import com.twilio.http.noauth.NoAuthRequest;
import com.twilio.http.noauth.NoAuthTwilioRestClient;

public class TokenCreator extends Creator<Token>{
private String grantType;
Expand Down Expand Up @@ -101,13 +78,13 @@ public TokenCreator setScope(final String scope){
}

@Override
public Token create(final TwilioRestClient client){
public Token create(final NoAuthTwilioRestClient client){
String path = "/v1/token";

path = path.replace("{"+"grant_type"+"}", this.grantType.toString());
path = path.replace("{"+"client_id"+"}", this.clientId.toString());

Request request = new Request(
NoAuthRequest request = new NoAuthRequest(
HttpMethod.POST,
Domains.PREVIEWIAM.toString(),
path
Expand All @@ -117,7 +94,7 @@ public Token create(final TwilioRestClient client){
Response response = client.request(request);
if (response == null) {
throw new ApiConnectionException("Token creation failed: Unable to connect to server");
} else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) {
} else if (!NoAuthTwilioRestClient.SUCCESS.test(response.getStatusCode())) {
RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper());
if (restException == null) {
throw new ApiException("Server Error, no content", response.getStatusCode());
Expand All @@ -127,7 +104,7 @@ public Token create(final TwilioRestClient client){

return Token.fromJson(response.getStream(), client.getObjectMapper());
}
private void addPostParams(final Request request) {
private void addPostParams(final NoAuthRequest request) {
if (grantType != null) {
request.addPostParam("grant_type", grantType);

Expand Down

0 comments on commit 8716eb1

Please sign in to comment.