# Connecting with Java

This guide explains how to establish a connection between a Java Spring Boot application and a Keycloak identity provider using the OAuth2 resource server configuration. It walks through the necessary setup, configuration, and creation of a protected endpoint that verifies Keycloak-issued access tokens.

## **Variables**

Certain parameters must be provided to integrate a Spring Boot application with Keycloak. Below is a breakdown of each required variable, its purpose, and where to find it. Here’s what each variable represents:

<table border="1" id="bkmrk-variable-description" style="width: 100%; border-collapse: collapse; border-color: rgb(0, 0, 0);"><thead><tr><th style="width: 12.5123%; border-color: rgb(0, 0, 0);">**Variable**

</th><th style="width: 47.5592%; border-color: rgb(0, 0, 0);">**Description**

</th><th style="width: 39.9285%; border-color: rgb(0, 0, 0);">**Purpose**

</th></tr></thead><tbody><tr><td style="width: 12.5123%; border-color: rgb(0, 0, 0);">`REALM`

</td><td style="width: 47.5592%; border-color: rgb(0, 0, 0);">The name of the Keycloak realm

</td><td style="width: 39.9285%; border-color: rgb(0, 0, 0);">Defines the authentication namespace

</td></tr><tr><td style="width: 12.5123%; border-color: rgb(0, 0, 0);">`CLIENT_ID`

</td><td style="width: 47.5592%; border-color: rgb(0, 0, 0);">Client ID from the Keycloak Admin Console

</td><td style="width: 39.9285%; border-color: rgb(0, 0, 0);">Identifies the Spring Boot app in Keycloak

</td></tr><tr><td style="width: 12.5123%; border-color: rgb(0, 0, 0);">`ISSUER_URI`

</td><td style="width: 47.5592%; border-color: rgb(0, 0, 0);"><span class="s1">Realm URL (e.g. </span>https://your-domain/realms/your-realm<span class="s1">)</span>

</td><td style="width: 39.9285%; border-color: rgb(0, 0, 0);">Used by Spring Security for token validation

</td></tr><tr><td style="width: 12.5123%; border-color: rgb(0, 0, 0);">`JWKS_URI`

</td><td style="width: 47.5592%; border-color: rgb(0, 0, 0);">URL to the JWKS endpoint (auto-resolved by Spring from ISSUER\_URI)

</td><td style="width: 39.9285%; border-color: rgb(0, 0, 0);">Used to fetch public keys for token signature verification

</td></tr></tbody></table>

These values can be found in the <span class="s1">**Keycloak Admin Console → Clients**</span> and under the <span class="s1">**OpenID Connect Endpoints**</span> section for your realm.

## **Prerequisites**

#### **Install Java and Maven**

Ensure Java is installed:

```
java -version
```

Ensure Maven is installed:

```
mvn -version
```

If not, download and install from [https://adoptium.net](https://adoptium.net) or [https://maven.apache.org](https://maven.apache.org).

## **Code**

Once all prerequisites are set up, create a new Spring Boot project with the following structure:

```
spring-keycloak-demo/
├── src/
│   └── main/
│       ├── java/com/example/demo/
│       │   ├── DemoApplication.java
│       │   └── HelloController.java
│       └── resources/
│           └── application.yml
├── pom.xml
```

**pom.xml**

```xml
<project xmlns="http://maven.apache.org/POM/4.0.0" ...>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>spring-keycloak-demo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <properties>
    <java.version>17</java.version>
    <spring.boot.version>3.1.5</spring.boot.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>
```

**application.yml**

```yaml
server:
  port: 8080

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: https://your-keycloak-domain/realms/your-realm
```

Replace <span class="s1">https://your-keycloak-domain/realms/your-realm</span> with the full issuer URI from your Keycloak realm.

**DemoApplication.java**

```java
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }
}
```

**HelloController.java**

```java
package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;

@RestController
public class HelloController {

  @GetMapping("/")
  public String publicEndpoint() {
    return "Welcome to the public endpoint.";
  }

  @GetMapping("/protected")
  public String protectedEndpoint(@AuthenticationPrincipal Jwt jwt) {
    return "Hello " + jwt.getClaimAsString("preferred_username") + ", you have accessed a protected route.";
  }
}
```

## **Execution**

1. Start the Spring Boot app with:

```
mvn spring-boot:run
```

2. Generate a JWT access token by logging in through your frontend or REST client (e.g., using Postman with client credentials).
3. Make a request to:

```
GET http://localhost:8080/protected
Authorization: Bearer <access_token>
```

If the token is valid:

- You will receive a welcome message with the Keycloak username
- If no token is provided or it’s invalid, you’ll get a <span class="s1">401 Unauthorized</span> error