# Java and Spring

> Sign users in and protect APIs from Java, Spring Boot or any servlet container with the 9in Java SDK or Spring Security.

Source: https://9in.io/docs/java/

Java apps use the official SDK, [`com.github.9in-io:java`](https://github.com/9in-io/java), in Spring Boot, Jakarta EE, Micronaut, Quarkus or plain Java: sign-in, token verification with live revocation, the Management API, webhooks and the adapter protocol. It has no dependencies and needs Java 11 or later. Android apps use the [Android SDK](https://9in.io/docs/native-apps/#android-the-9in-sdk), which is built on it. Spring Security's own `oauth2Login()` works with 9in too.

## Install

The SDK is on JitPack. With Gradle:

```kotlin
repositories {
    mavenCentral()
    maven { url = uri("https://jitpack.io") }
}

dependencies {
    implementation("com.github.9in-io:java:v0.1.0")
}
```

With Maven, add the `https://jitpack.io` repository and the dependency `com.github.9in-io:java:v0.1.0`.

## Sign users in

Web apps sign users in as a **confidential client** (see [Server-rendered apps](https://9in.io/docs/server-apps/) for how that works). Create the application first: **Applications → Create application → Regular Web App**, with your callback URL (for example `https://app.acme.com/nine/callback`) and logout URL, and copy the client ID and secret.

`AuthClient` builds the sign-in URL and finishes the sign-in on your callback; you keep the pending sign-in and the tokens in the user's session:

```java
AuthClient auth = AuthClient.fromEnv();   // NINE_ISSUER, NINE_CLIENT_ID, NINE_CLIENT_SECRET, NINE_REDIRECT_URI

// GET /nine/login
Login login = auth.createLogin(LoginOptions.builder().returnTo("/dashboard").build());
session.setAttribute("nine.pending", login.pending().toJson());
response.sendRedirect(login.url());

// GET /nine/callback: checks state, iss and PKCE, verifies the ID token
String pending = (String) session.getAttribute("nine.pending");
session.removeAttribute("nine.pending");
TokenSet tokens = auth.handleCallback(request.getRequestURL() + "?" + request.getQueryString(),
    pending == null ? null : PendingLogin.fromJson(pending));
session.setAttribute("nine.tokens", tokens.toJson());   // tokens.claims(): sub, email, name, …
```

`LoginOptions.builder().screen("signup")` opens the sign-up form. Before calling your API, use `auth.ensureFresh(tokens, Duration.ofSeconds(60))`: it refreshes the access token near expiry, and 9in rotates the refresh token, so store the set you get back. To sign out, call `auth.revoke(tokens.refreshToken(), "refresh_token")` and redirect to `auth.logoutUrl(tokens.idToken(), "https://app.acme.com/", null)`.

## Sign in with Spring Security

Spring Security's own `oauth2Login()` works with 9in. Register `https://app.acme.com/login/oauth2/code/nine` as a callback URL and set:

```yaml
spring.security.oauth2.client:
  registration.nine:
    client-id: ${NINE_CLIENT_ID}
    client-secret: ${NINE_CLIENT_SECRET}
    scope: openid,profile,email,offline_access
  provider.nine.issuer-uri: ${NINE_ISSUER}
```

Add PKCE with `OAuth2AuthorizationRequestCustomizers.withPkce()` and sign out at 9in with `OidcClientInitiatedLogoutSuccessHandler`. Spring verifies ID tokens with RS256 by default; if your tenant's default key is ES, PS or EdDSA, set `OidcIdTokenDecoderFactory.setJwsAlgorithmResolver`. The [SDK's README](https://github.com/9in-io/java#spring-security-sign-in-with-oauth2login) has the full configuration.

## Protect your API

```java
TokenVerifier verifier = TokenVerifier.builder()
    .issuer("https://acme.9in.io")
    .audience("https://api.acme.com")
    .build();
AccessTokenClaims claims = verifier.verify(request.getHeader("Authorization"), "orders:read");
```

It checks the signature with every algorithm of your key library, the token type, issuer, expiry, audience and scopes, and throws `InvalidTokenException` (401) or `InsufficientScopeException` (403). For revocation that takes effect at once, use `HybridTokenVerifier` with a confidential application's client ID and secret, and pass your webhooks to `verifier.handleEvent(…)` ([hybrid verification](https://9in.io/docs/protecting-apis/)).

In Spring Boot, plug it into the resource server:

```java
http.securityMatcher("/api/**")
    .authorizeHttpRequests(a -> a.anyRequest().authenticated())
    .oauth2ResourceServer(o -> o.opaqueToken(t -> t.introspector(new NineOpaqueTokenIntrospector(verifier))))
    .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
    .csrf(c -> c.disable());
```

Scopes become `SCOPE_` authorities, so `hasAuthority("SCOPE_orders:read")` works. Keep the API chain stateless, as above, so a browser's session cookie can't call it. In a servlet container without Spring, use `new BearerTokenFilter(verifier, "orders:read")`.

## Manage users, webhooks and your own database

- `ManagementClient.fromEnv()` creates, finds, updates, blocks and deletes users, creates login links and ends sessions. See [Management API](https://9in.io/docs/reference/management-api/).
- `Webhooks.verify(secret, rawBody, signatureHeader, path)` verifies a webhook and returns the event; `EventDeduplicator` processes each event once. `WebhookServlet` does both in a servlet container. See [Webhooks](https://9in.io/docs/webhooks/).
- Implement `io.ninein.adapter.Adapter` and serve it with `AdapterHandler` (or `AdapterServlet`) to keep users in [your own database](https://9in.io/docs/own-database/).

## Machine to machine and devices

`auth.clientCredentials("https://api.acme.com", "orders:read")` gets a token for your own back end ([machine to machine](https://9in.io/docs/machine-to-machine/)). `auth.startDeviceAuthorization(null)` and `auth.pollDeviceAuthorization(device)` sign in a CLI or TV ([device flow](https://9in.io/docs/devices/)).
