Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Support for bearer token authentication and no authentication and PUT method in REST calls #803

Merged
merged 4 commits into from
Jun 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,12 @@ public class Example {
}
}
```
### Initialize the client when endpoints does not use basic authentication
The above example shows how to initialize the client in case the endpoints use basic authentication. When the endpoint does not require any authentication, use TwilioNoAuth client instead.
There are endpoints like Organization domain which uses bearer token authentication. Custom Clients needs to be used in such cases and initialize them with the values required for access token generation.

To bypass the initialization step you can also use a custom token manager implementation. Token manager class should implement the Token interface and call a token generation endpoint of your choice.
Detailed examples [here](https://github.com/twilio/twilio-java/tree/main/examples)

### Environment Variables

Expand Down
26 changes: 26 additions & 0 deletions examples/BearerTokenAuthentication.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
class BearerTokenAuthenticationExamples {
public static void main {

private static final String GRANT_TYPE = "grant_type_to_be_used";
private static final String CLIENT_SID =
"client_id_of_the_organization";
private static final String CLIENT_SECRET = "client_secret_of_organization";
private static final String ORGANISATION_ID = "id_of_the_organization";

//Getting access token - Method #1
TwilioOrgsTokenAuth.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
//TwilioOrgsTokenAuth.setTokenManager(new CustomTokenManagerImpl(GRANT_TYPE, CLIENT_ID, CLIENT_SECRET));

fetchAccountDetails();
}

private static void fetchAccountDetails() {
ResourceSet<Account> accountSet = Account.reader(ORGANISATION_ID).read();
String accountSid = accountSet.iterator().next().getAccountSid();
System.out.println(accountSid);
}
}
11 changes: 11 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,17 @@
<version>1.10.19</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>4.4.0</version>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
Expand Down
1 change: 1 addition & 0 deletions src/main/java/com/twilio/Domains.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ public enum Domains {
NUMBERS("numbers"),
OAUTH("oauth"),
PREVIEW("preview"),
PREVIEWIAM("preview-iam"),
PRICING("pricing"),
PROXY("proxy"),
ROUTES("routes"),
Expand Down
48 changes: 48 additions & 0 deletions src/main/java/com/twilio/TwilioNoAuth.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package com.twilio;

import com.twilio.annotations.Preview;
import com.twilio.http.noauth.NoAuthTwilioRestClient;
import lombok.Getter;

import java.util.List;
import com.twilio.exception.AuthenticationException;

@Preview
public class TwilioNoAuth {
@Getter
private static List<String> userAgentExtensions;
private static String region = System.getenv("TWILIO_REGION");
private static String edge = System.getenv("TWILIO_EDGE");

private static volatile NoAuthTwilioRestClient noAuthTwilioRestClient;

private TwilioNoAuth() {
}

public static NoAuthTwilioRestClient getRestClient() {
if (TwilioNoAuth.noAuthTwilioRestClient == null) {
synchronized (TwilioNoAuth.class) {
if (TwilioNoAuth.noAuthTwilioRestClient == null) {
TwilioNoAuth.noAuthTwilioRestClient = buildOAuthRestClient();
}
}
}
return TwilioNoAuth.noAuthTwilioRestClient;
}

private static NoAuthTwilioRestClient buildOAuthRestClient() {

NoAuthTwilioRestClient.Builder builder = new NoAuthTwilioRestClient.Builder();

if (userAgentExtensions != null) {
builder.userAgentExtensions(TwilioNoAuth.userAgentExtensions);
}

builder.region(TwilioNoAuth.region);
builder.edge(TwilioNoAuth.edge);

return builder.build();
}


}
106 changes: 106 additions & 0 deletions src/main/java/com/twilio/TwilioOrgsTokenAuth.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
package com.twilio;

import com.twilio.annotations.Preview;
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 TwilioOrgsTokenAuth {
private static String accessToken;
@Getter
private static List<String> userAgentExtensions;
private static String region = System.getenv("TWILIO_REGION");
private static String edge = System.getenv("TWILIO_EDGE");
private static volatile BearerTokenTwilioRestClient restClient;
@Getter @Setter
private static TokenManager tokenManager;

private static volatile ExecutorService executorService;

private TwilioOrgsTokenAuth() {
}

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");
}
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() {
if (TwilioOrgsTokenAuth.restClient == null) {
synchronized (TwilioOrgsTokenAuth.class) {
if (TwilioOrgsTokenAuth.restClient == null) {
TwilioOrgsTokenAuth.restClient = buildOAuthRestClient();
}
}
}
return TwilioOrgsTokenAuth.restClient;
}
/**
* Returns the Twilio executor service.
*
* @return the Twilio executor service
*/
public static ExecutorService getExecutorService() {
if (TwilioOrgsTokenAuth.executorService == null) {
synchronized (TwilioOrgsTokenAuth.class) {
if (TwilioOrgsTokenAuth.executorService == null) {
TwilioOrgsTokenAuth.executorService = Executors.newCachedThreadPool();
}
}
}
return TwilioOrgsTokenAuth.executorService;
}

private static BearerTokenTwilioRestClient buildOAuthRestClient() {

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

if (userAgentExtensions != null) {
builder.userAgentExtensions(TwilioOrgsTokenAuth.userAgentExtensions);
}

builder.region(TwilioOrgsTokenAuth.region);
builder.edge(TwilioOrgsTokenAuth.edge);
if(TwilioOrgsTokenAuth.tokenManager == null){
throw new AuthenticationException("Either initialize the authentications class or pass a custom token manager");
}
builder.tokenManager(TwilioOrgsTokenAuth.tokenManager);

return builder.build();
}

/**
* Invalidates the volatile state held in the Twilio singleton.
*/
private static void invalidate() {
TwilioOrgsTokenAuth.restClient = null;
TwilioOrgsTokenAuth.tokenManager = null;
}


}
9 changes: 9 additions & 0 deletions src/main/java/com/twilio/annotations/Beta.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.twilio.annotations;

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Beta {
String value() default "This class/method is under beta and is subjected to change. Use with caution.";
}
12 changes: 12 additions & 0 deletions src/main/java/com/twilio/annotations/Preview.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.twilio.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Preview {
String value() default "This class/method is under preview and is subjected to change. Use with caution.";
}
50 changes: 50 additions & 0 deletions src/main/java/com/twilio/base/bearertoken/Creator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package com.twilio.base.bearertoken;

import com.twilio.TwilioOrgsTokenAuth;
import com.twilio.http.bearertoken.BearerTokenTwilioRestClient;

import java.util.concurrent.CompletableFuture;

/**
* Executor for creation of a resource.
*
* @param <T> type of the resource
*/
public abstract class Creator<T extends Resource> {

/**
* Execute an async request using default client.
*
* @return future that resolves to requested object
*/
public CompletableFuture<T> createAsync() {
return createAsync(TwilioOrgsTokenAuth.getRestClient());
}

/**
* Execute an async request using specified client.
*
* @param client client used to make request
* @return future that resolves to requested object
*/
public CompletableFuture<T> createAsync(final BearerTokenTwilioRestClient client) {
return CompletableFuture.supplyAsync(() -> create(client), TwilioOrgsTokenAuth.getExecutorService());
}

/**
* Execute a request using default client.
*
* @return Requested object
*/
public T create() {
return create(TwilioOrgsTokenAuth.getRestClient());
}

/**
* Execute a request using specified client.
*
* @param client client used to make request
* @return Requested object
*/
public abstract T create(final BearerTokenTwilioRestClient client);
}
51 changes: 51 additions & 0 deletions src/main/java/com/twilio/base/bearertoken/Deleter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.twilio.base.bearertoken;

import com.twilio.Twilio;
import com.twilio.TwilioOrgsTokenAuth;
import com.twilio.http.bearertoken.BearerTokenTwilioRestClient;

import java.util.concurrent.CompletableFuture;

/**
* Executor for deletes of a resource.
*
* @param <T> type of the resource
*/
public abstract class Deleter<T extends Resource> {

/**
* Execute an async request using default client.
*
* @return future that resolves to true if the object was deleted
*/
public CompletableFuture<Boolean> deleteAsync() {
return deleteAsync(TwilioOrgsTokenAuth.getRestClient());
}

/**
* Execute an async request using specified client.
*
* @param client client used to make request
* @return future that resolves to true if the object was deleted
*/
public CompletableFuture<Boolean> deleteAsync(final BearerTokenTwilioRestClient client) {
return CompletableFuture.supplyAsync(() -> delete(client), Twilio.getExecutorService());
}

/**
* Execute a request using default client.
*
* @return true if the object was deleted
*/
public boolean delete() {
return delete(TwilioOrgsTokenAuth.getRestClient());
}

/**
* Execute a request using specified client.
*
* @param client client used to make request
* @return true if the object was deleted
*/
public abstract boolean delete(final BearerTokenTwilioRestClient client);
}
Loading
Loading