Java Profile Service
Read and manage user profiles, consents and the activity log from your Java backend with ProfileClient
ProfileClient calls the Hawcx Profile API: the profile, consent records and
activity log Hawcx keeps for each user. It runs on your backend only, and it
works in two modes:
| Mode | How you get it | What it can do |
|---|---|---|
| As your backend | ProfileClient.builder(oauth).build() | Any user in your project. The scopes come from What can this backend do? in the Admin Console. |
| As the signed-in user | profiles.forUser(idToken) | Only that user's own profile, consents and activity (/v1/me). |
Available in com.hawcx:hawcx-java-sdk 0.7.0 and later, in the
com.hawcx.profile package.
Before you start
In the Admin Console, open your project → Settings → OAuth tab, and in OIDC Clients edit the client your backend signs in with:
- Set Client authentication to Enhanced (private_key_jwt) and download the private key. See Confidential Clients.
- Turn on Profile access (hx_profile). Only a project admin can change it.
- Under What can this backend do?, pick View only or View, edit & delete.
- To act for signed-in users, turn on Let users manage their own profile.
- Save the client.
View only grants users:read, consent:read and audit:read.
View, edit & delete adds users:write, users:delete and consent:write.
Let users manage their own profile grants profile:self. When you turn
on profile access, the console grants View only by default.
Use the same client for sign-in
forUser only accepts an ID token that was issued to this same client. If
users sign in through a different client, the exchange fails with
invalid_grant.
Set up
Build the client once at startup and reuse it; it is thread-safe. It caches its
access token and refreshes it before it expires. If a refresh fails while the current token is
still valid (for any reason), the client keeps using it, so a short outage at
the token endpoint does not fail your calls. It then waits 30 seconds, or until
the token expires if that is sooner, before it tries to refresh early again. Tokens that forUser gets are not refreshed early: they are
refreshed only when they expire.
import com.hawcx.oauth.ClientAssertionSigner;
import com.hawcx.oauth.ExchangeOptions;
import com.hawcx.oauth.ExchangeResult;
import com.hawcx.oauth.HawcxOauthClient;
import com.hawcx.oauth.HawcxOauthIssuerConfig;
import com.hawcx.profile.*;
HawcxOauthClient oauth = HawcxOauthClient
.fromIssuer(HawcxOauthIssuerConfig.builder()
.issuer(System.getenv("HAWCX_BASE_URL"))
.configId(System.getenv("HAWCX_CONFIG_ID"))
.clientId(System.getenv("HAWCX_CLIENT_ID"))
.build())
.withClientAssertion(
ClientAssertionSigner.ed25519FromJwk(System.getenv("HAWCX_OAUTH_PRIVATE_KEY_JWK")));
ProfileClient profiles = ProfileClient.builder(oauth).build();build() throws IllegalStateException if oauth was not built with
fromIssuer and withClientAssertion.
| Builder method | Default | Description |
|---|---|---|
baseUrl(String) | {issuer}/profile | Profile API base URL. Must be https (plain http only on localhost). |
scopes(List<String>) | all the client's scopes | Ask for fewer scopes, e.g. List.of("users:read"). Omit it to use all of them; scopes(List.of()) throws IllegalArgumentException. |
audience(String) | hx-profile | Token-exchange audience for forUser. Change it only if Hawcx support gives you a different value. |
timeout(Duration) | 10 seconds | Time allowed for each profile request, response body included. Token-endpoint calls use HawcxOauthClient's own limits: 5 seconds to connect and 15 seconds for the whole exchange, including the body. |
maxRetries(int) | 2 | Retries for GET, PUT and DELETE, and for failures getting the access token. See Retries. |
httpClient(HttpClient) | built-in | Your own HttpClient (proxy, TLS). It must use Redirect.NEVER. |
As your backend
Profile user = profiles.getUser("user-123");
// null clears a field (not `status`, which can't be cleared); a field you don't set is unchanged.
profiles.updateUser("user-123", new ProfilePatch().displayName("Ada").locale(null));
profiles.setConsent("user-123", "marketing", new Consent.Input("granted"));
for (Profile p : profiles.iterUsers(null, "active", null)) {
System.out.println(p.userId() + " " + p.email());
}| Method | Returns | Scope |
|---|---|---|
getUser(userId) | Profile | users:read |
listUsers(), listUsers(email, status, cursor, limit) | Page<Profile> | users:read |
iterUsers(), iterUsers(email, status, limit) | Iterable<Profile> | users:read |
createUser(userId, ProfilePatch) | Profile | users:write |
updateUser(userId, ProfilePatch) | Profile | users:write |
replaceUser(userId, ProfilePatch) | Profile | users:write |
deleteUser(userId) | void | users:delete |
getConsents(userId), getConsents(userId, cursor, limit) | ConsentsPage | consent:read |
setConsent(userId, purpose, Consent.Input) | Consent | consent:write |
getAudit(userId), getAudit(userId, cursor, limit) | Page<AuditEvent> | audit:read |
iterAudit(userId, limit) | Iterable<AuditEvent> | audit:read |
forUser(idToken) | UserProfileClient | — |
Pass null for any filter, cursor or limit you don't need. createUser adds a
profile for a user who already exists in Hawcx; the patch must set
givenName and familyName. It fails with 404 if there is no such user and
409 if they already have a profile.
replaceUser replaces the whole profile: it needs the given and family name,
and clears every other optional field you leave out (status is kept). Use
the update method to change only some fields.
As the signed-in user
Pass the ID token you just received at sign-in, and make the calls straight away.
Only right after sign-in
An ID token is valid for 60 seconds by default, and the token that
forUser gets lasts no longer than the ID token. Don't store the ID token
for later. To read or change a user's profile later (for example, on an
account page), use the backend methods with their user_id (the sub claim).
Once the ID token expires, calls fail with invalid_grant.
ExchangeResult result = oauth.exchangeCode(
ExchangeOptions.builder().code(code).codeVerifier(codeVerifier).build());
UserProfileClient me = profiles.forUser(result.idToken());
Profile mine = me.getMe();
me.updateMe(new ProfilePatch().givenName("Ada"));
me.setMyConsent("marketing", new Consent.Input("withdrawn"));| Method | Returns |
|---|---|
getMe() | Profile |
updateMe(ProfilePatch) | Profile |
getMyConsents(), getMyConsents(cursor, limit) | ConsentsPage |
setMyConsent(purpose, Consent.Input) | Consent |
getMyAudit(), getMyAudit(cursor, limit) | Page<AuditEvent> |
iterMyAudit(limit) | Iterable<AuditEvent> |
updateMe takes only the fields a user may change about themselves: givenName, familyName, displayName, dateOfBirth, address, locale and timezone. Setting any other field (for example status) throws IllegalArgumentException before any request.
Data shapes
Results are records with camelCase accessors.
| Type | Fields |
|---|---|
Profile | userId, tenantId, email, emailVerified, phone, phoneVerified, givenName, familyName, displayName, dateOfBirth, address, locale, timezone, marketingOptIn, customAttributes, status, createdAt, updatedAt |
ProfilePatch (input) | Setters givenName, familyName, displayName, dateOfBirth, address, locale, timezone, status. Only the fields you call are sent. |
Consent.Input (input) | status ("granted" or "withdrawn"), and optional lawfulBasis, noticeVersion, source |
Consent | consentId, purpose, status, lawfulBasis, noticeVersion, source, createdAt |
AuditEvent | eventId, actor, action, resource, beforeHash, afterHash, detail, createdAt |
Lists return a Page with items() and nextCursor(). Pass nextCursor()
back as the cursor to get the next page; it is null on the last page. An empty string also ends paging. limit
is 1–200 (default 50). Consents return a ConsentsPage with current(),
history() and nextCursor(), where current() maps each purpose to its
latest consent. The iter* methods follow every page for you.
Errors
An ID or consent purpose that is empty, ., .., or contains /, \ or a
control character is rejected before any request with IllegalArgumentException.
A failed call throws ProfileApiException, a subclass of HawcxException.
Getting the access token can also fail with HawcxOauthException (for
example, invalid_scope when the client has no profile access).
try {
profiles.getUser("user-123");
} catch (ProfileApiException e) {
if (e.getStatus() != 404) throw e;
// no such user
}| Getter | Description |
|---|---|
getStatus() | HTTP status; 0 if no response arrived (network error or timeout). |
getTitle(), getDetail(), getType(), getInstance() | The API's error fields. |
getRequestId() | Include this when you contact support. |
getMissing() | On 403: the scopes the client is missing. null when the API leaves it out. |
getFields() | On 422, when the API names them: the fields that were rejected. null when the API leaves it out. |
getRetryAfter() | Seconds to wait, when the API sent one. |
getRawBody() | The response body as text (up to 4,096 characters), for example a gateway's HTML error page. Never part of the message. |
A call that succeeds on the wire but returns an unusable body also throws ProfileApiException, with that 2xx status:
Invalid JSON response: the body isn't JSON.Unexpected response body: the body is JSON but not the expected object, or the API answered 204 to a call that returns a value.deleteUseris the exception: any 2xx with an empty body, a whitespace-only body or a body that is not a JSON object counts as success.Response body read failed: the response started but its body never arrived in full: the connection dropped, or the body did not finish withintimeout. The request reached the API, so a create or update may have happened; check before you try again.
On a 2xx, the raw body is kept only for a markup page such as HTML or XML (after any whitespace or BOM, it starts with <); otherwise it is null, because a damaged response may still hold a user's profile.
Retries
GET,PUTandDELETEare retried up tomaxRetriestimes on network errors and on 408, 429, 502, 503 and 504. The client waits as long as theRetry-Afterheader asks (up to 30 seconds), otherwise a short random backoff. It honours only the delta-seconds form ofRetry-After; it ignores an HTTP date, so it uses the short backoff andgetRetryAfter()isnull.POSTandPATCHare never retried once the Profile API has accepted the token, so a create or update never runs twice.- On 401, for every method, the client gets a new token and tries once more. The API rejects a request with an invalid token before doing anything, so this can't repeat a change. If you used
forUserand getting the new token then fails because the ID token has expired, the call throws the original 401 error (ProfileApiException, status 401), not the token error. - If getting the access token fails with a network error or 408, 429, 502, 503 or 504, the call is retried whatever its method, because nothing was sent to the Profile API yet. These retries count toward
maxRetriesand use the short backoff only. - A retried
deleteUserthat ends in 404 succeeds if an earlier attempt may already have deleted the user: that attempt was sent but got no response (a failure to connect doesn't count), had its 2xx body cut off mid-read, or got 504. Otherwise the 404 is thrown. - Redirects are never followed, so the token is never sent to another host.
Next steps
- Java API Reference — the rest of
com.hawcx:hawcx-java-sdk. - Confidential Clients (private_key_jwt) — the key this client signs with.
Last updated on