Skip to content

Commit f2753cd

Browse files
authored
Patch: Fixed Readme links and added Examples (#836)
1 parent df0ace1 commit f2753cd

File tree

4 files changed

+360
-31
lines changed

4 files changed

+360
-31
lines changed

.github/workflows/claude-code-review.yml

Lines changed: 0 additions & 11 deletions
This file was deleted.

EXAMPLES.md

Lines changed: 335 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,335 @@
1+
# Examples using auth0-java
2+
3+
- [Error handling](#error-handling)
4+
- [HTTP Client configuration](#http-client-configuration)
5+
- [Management API usage](#management-api-usage)
6+
- [Verifying an ID token](#verifying-an-id-token)
7+
- [Organizations](#organizations)
8+
- [Asynchronous operations](#asynchronous-operations)
9+
10+
## Error handling
11+
12+
### Management API errors
13+
14+
The Management API uses a unified `ManagementApiException` class, which provides access to the HTTP status code, response body, headers, and message of the error response.
15+
16+
```java
17+
import com.auth0.client.mgmt.core.ManagementApiException;
18+
19+
try {
20+
GetUserResponseContent user = client.users().get("user_id");
21+
} catch (ManagementApiException e) {
22+
int statusCode = e.statusCode();
23+
Object body = e.body();
24+
Map<String, List<String>> headers = e.headers();
25+
String message = e.getMessage();
26+
}
27+
```
28+
29+
### Authentication API errors
30+
31+
The Authentication API uses `APIException` for error handling.
32+
33+
```java
34+
import com.auth0.exception.APIException;
35+
36+
try {
37+
TokenHolder holder = authAPI.requestToken("https://{YOUR_DOMAIN}/api/v2/").execute().getBody();
38+
} catch (APIException e) {
39+
int statusCode = e.getStatusCode();
40+
String description = e.getDescription();
41+
String error = e.getError();
42+
}
43+
```
44+
45+
## HTTP Client configuration
46+
47+
### Authentication API
48+
49+
The Authentication API client uses the OkHttp networking library to make HTTP requests.
50+
The client can be configured by building a `DefaultHttpClient` and providing it to the API client.
51+
52+
```java
53+
Auth0HttpClient httpClient = DefaultHttpClient.newBuilder()
54+
// configure as needed
55+
.build();
56+
57+
AuthAPI auth = AuthAPI.newBuilder("{YOUR_DOMAIN}", "{YOUR_CLIENT_ID}", "{YOUR_CLIENT_SECRET}")
58+
.withHttpClient(httpClient)
59+
.build();
60+
```
61+
62+
If the `DefaultHttpClient` does not support your required networking client configuration, you may choose to implement
63+
your own client by implementing the `Auth0HttpClient` interface and providing it to the API client. This is an advanced
64+
use case and should be used only when necessary.
65+
66+
### Management API
67+
68+
The Management API client uses `ManagementApi` as the main entry point.
69+
You can configure a custom `OkHttpClient` via the builder:
70+
71+
```java
72+
import com.auth0.client.mgmt.ManagementApi;
73+
74+
OkHttpClient okHttpClient = new OkHttpClient.Builder()
75+
// configure as needed
76+
.build();
77+
78+
ManagementApi client = ManagementApi.builder()
79+
.domain("{YOUR_DOMAIN}")
80+
.token("{YOUR_API_TOKEN}")
81+
.httpClient(okHttpClient)
82+
.build();
83+
```
84+
85+
## Management API usage
86+
87+
### Creating a client with a static token
88+
89+
```java
90+
import com.auth0.client.mgmt.ManagementApi;
91+
92+
ManagementApi client = ManagementApi.builder()
93+
.domain("{YOUR_DOMAIN}")
94+
.token("{YOUR_API_TOKEN}")
95+
.build();
96+
```
97+
98+
### Creating a client with client credentials (recommended)
99+
100+
When using client credentials, the SDK automatically fetches and caches access tokens, refreshing them before expiry.
101+
102+
```java
103+
import com.auth0.client.mgmt.ManagementApi;
104+
105+
ManagementApi client = ManagementApi.builder()
106+
.domain("{YOUR_DOMAIN}")
107+
.clientCredentials("{YOUR_CLIENT_ID}", "{YOUR_CLIENT_SECRET}")
108+
.build();
109+
```
110+
111+
You can also specify a custom audience:
112+
113+
```java
114+
ManagementApi client = ManagementApi.builder()
115+
.domain("{YOUR_DOMAIN}")
116+
.clientCredentials("{YOUR_CLIENT_ID}", "{YOUR_CLIENT_SECRET}")
117+
.audience("{YOUR_AUDIENCE}")
118+
.build();
119+
```
120+
121+
### Creating a client with advanced options
122+
123+
```java
124+
ManagementApi client = ManagementApi.builder()
125+
.domain("{YOUR_DOMAIN}")
126+
.clientCredentials("{YOUR_CLIENT_ID}", "{YOUR_CLIENT_SECRET}")
127+
.timeout(30) // timeout in seconds (default: 60)
128+
.maxRetries(3) // max retries (default: 2)
129+
.addHeader("X-Custom-Header", "value")
130+
.build();
131+
```
132+
133+
### Accessing resources
134+
135+
The Management API is organized into resource clients:
136+
137+
```java
138+
// Get a user
139+
GetUserResponseContent user = client.users().get("user_id");
140+
141+
// Get a role
142+
GetRoleResponseContent role = client.roles().get("role_id");
143+
144+
// Create a user
145+
CreateUserResponseContent newUser = client.users().create(
146+
CreateUserRequestContent.builder()
147+
.email("user@example.com")
148+
.connection("Username-Password-Authentication")
149+
.password("securePassword123!")
150+
.build()
151+
);
152+
153+
// Update a user
154+
UpdateUserResponseContent updatedUser = client.users().update(
155+
"user_id",
156+
UpdateUserRequestContent.builder()
157+
.name("Updated Name")
158+
.build()
159+
);
160+
161+
// Delete a user
162+
client.users().delete("user_id");
163+
```
164+
165+
### Pagination
166+
167+
List operations return a `SyncPagingIterable` that supports automatic pagination:
168+
169+
```java
170+
import com.auth0.client.mgmt.core.SyncPagingIterable;
171+
import com.auth0.client.mgmt.types.ListUsersRequestParameters;
172+
import com.auth0.client.mgmt.types.UserResponseSchema;
173+
174+
SyncPagingIterable<UserResponseSchema> users = client.users().list(
175+
ListUsersRequestParameters.builder()
176+
.perPage(50)
177+
.build()
178+
);
179+
180+
// Iterate through all pages automatically
181+
for (UserResponseSchema user : users) {
182+
System.out.println(user.getEmail());
183+
}
184+
185+
// Or access pages manually
186+
List<UserResponseSchema> pageItems = users.getItems();
187+
while (users.hasNext()) {
188+
pageItems = users.nextPage().getItems();
189+
}
190+
```
191+
192+
### Accessing raw HTTP responses
193+
194+
Use `withRawResponse()` to access HTTP response metadata:
195+
196+
```java
197+
import com.auth0.client.mgmt.core.ManagementApiHttpResponse;
198+
199+
ManagementApiHttpResponse<GetUserResponseContent> response = client.users()
200+
.withRawResponse()
201+
.get("user_id");
202+
203+
GetUserResponseContent user = response.body();
204+
Map<String, List<String>> headers = response.headers();
205+
```
206+
207+
### Nested sub-resources
208+
209+
Some resources have nested sub-clients:
210+
211+
```java
212+
// List a user's roles
213+
SyncPagingIterable<Role> roles = client.users().roles().list("user_id");
214+
215+
// List a user's permissions
216+
SyncPagingIterable<Permission> permissions = client.users().permissions().list("user_id");
217+
218+
// List organization members
219+
SyncPagingIterable<OrganizationMember> members = client.organizations().members().list("org_id");
220+
```
221+
222+
## Verifying an ID token
223+
224+
This library also provides the ability to validate an OIDC-compliant ID Token, according to the [OIDC Specification](https://openid.net/specs/openid-connect-core-1_0-final.html#IDTokenValidation).
225+
226+
### Verifying an ID Token signed with the RS256 signing algorithm
227+
228+
To verify an ID Token that is signed using the RS256 signing algorithm, you will need to provide an implementation of
229+
`PublicKeyProvider` that will return the public key used to verify the token's signature. The example below demonstrates how to use the `JwkProvider` from the [jwks-rsa-java](https://github.com/auth0/jwks-rsa-java) library:
230+
231+
```java
232+
JwkProvider provider = new JwkProviderBuilder("https://your-domain.auth0.com").build();
233+
SignatureVerifier signatureVerifier = SignatureVerifier.forRS256(new PublicKeyProvider() {
234+
@Override
235+
public RSAPublicKey getPublicKeyById(String keyId) throws PublicKeyProviderException {
236+
try {
237+
return (RSAPublicKey) provider.get(keyId).getPublicKey();
238+
} catch (JwkException jwke) {
239+
throw new PublicKeyProviderException("Error obtaining public key", jwke);
240+
}
241+
}
242+
}
243+
244+
IdTokenVerifier idTokenVerifier = IdTokenVerifier.init("https://your-domain.auth0.com/","your-client-id", signatureVerifier).build();
245+
246+
try {
247+
idTokenVerifier.verify("token", "expected-nonce");
248+
} catch(IdTokenValidationException idtve) {
249+
// Handle invalid token exception
250+
}
251+
```
252+
253+
### Verifying an ID Token signed with the HS256 signing algorithm
254+
255+
To verify an ID Token that is signed using the HS256 signing algorithm:
256+
257+
```java
258+
SignatureVerifier signatureVerifier = SignatureVerifier.forHS256("your-client-secret");
259+
IdTokenVerifier idTokenVerifier = IdTokenVerifier.init("https://your-domain.auth0.com/","your-client-id", signatureVerifier).build();
260+
261+
try {
262+
idTokenVerifier.verify("token", "expected-nonce");
263+
} catch(IdTokenValidationException idtve) {
264+
// Handle invalid token exception
265+
}
266+
```
267+
268+
## Organizations
269+
270+
[Organizations](https://auth0.com/docs/organizations) is a set of features that provide better support for developers who build and maintain SaaS and Business-to-Business (B2B) applications.
271+
272+
Note that Organizations is currently only available to customers on our Enterprise and Startup subscription plans.
273+
274+
### Log in to an organization
275+
276+
Log in to an organization by using `withOrganization()` when building the Authorization URL:
277+
278+
```java
279+
AuthAPI auth = AuthAPI.newBuilder("{YOUR_DOMAIN}", "{YOUR_CLIENT_ID}", "{YOUR_CLIENT_SECRET}").build();
280+
String url = auth.authorizeUrl("https://me.auth0.com/callback")
281+
.withOrganization("{YOUR_ORGANIZATION_ID}")
282+
.build();
283+
```
284+
285+
**Important!** When logging into an organization, it is important to ensure the `org_id` claim of the ID Token matches the expected organization value. The `IdTokenVerifier` can be configured with an expected `org_id` claim value, as the example below demonstrates.
286+
For more information, please read [Work with Tokens and Organizations](https://auth0.com/docs/organizations/using-tokens) on Auth0 Docs.
287+
```java
288+
IdTokenVerifier.init("{ISSUER}", "{AUDIENCE}", signatureVerifier)
289+
.withOrganization("{ORG_ID}")
290+
.build()
291+
.verify(jwt);
292+
```
293+
294+
### Accept user invitations
295+
296+
Accept a user invitation by using `withInvitation()` when building the Authorization URL:
297+
298+
```java
299+
AuthAPI auth = AuthAPI.newBuilder("{YOUR_DOMAIN}", "{YOUR_CLIENT_ID}", "{YOUR_CLIENT_SECRET}").build();
300+
String url = auth.authorizeUrl("https://me.auth0.com/callback")
301+
.withOrganization("{YOUR_ORGANIZATION_ID}")
302+
.withInvitation("{YOUR_INVITATION_ID}")
303+
.build();
304+
```
305+
306+
## Asynchronous operations
307+
308+
### Management API
309+
310+
The Management API provides an async client that returns `CompletableFuture` for all operations:
311+
312+
```java
313+
import com.auth0.client.mgmt.AsyncManagementApi;
314+
import com.auth0.client.mgmt.core.ClientOptions;
315+
316+
AsyncManagementApi asyncClient = new AsyncManagementApi(clientOptions);
317+
318+
// Async user retrieval
319+
CompletableFuture<GetUserResponseContent> future = asyncClient.users().get("user_id");
320+
future.thenAccept(user -> {
321+
System.out.println(user.getEmail());
322+
});
323+
```
324+
325+
### Authentication API
326+
327+
The Authentication API supports async operations via the `executeAsync()` method:
328+
329+
```java
330+
AuthAPI auth = AuthAPI.newBuilder("{YOUR_DOMAIN}", "{YOUR_CLIENT_ID}", "{YOUR_CLIENT_SECRET}").build();
331+
CompletableFuture<TokenHolder> future = auth.requestToken("https://{YOUR_DOMAIN}/api/v2/").executeAsync();
332+
future.thenAccept(holder -> {
333+
String accessToken = holder.getBody().getAccessToken();
334+
});
335+
```

0 commit comments

Comments
 (0)