import UriInputField from '@/mdx-components/UriInputField';
import Steps from '@/mdx-components/Steps';
import Step from '@/mdx-components/Step';
import CustomDomainEndpointNotice from '@/mdx-components/CustomDomainEndpointNotice';

import Checkpoint from '../../fragments/_checkpoint.md';
import RedirectUrisWeb from '../../fragments/_redirect-uris-web.mdx';

<Steps>

<Step title="Get started">

This tutorial will show you how to integrate Logto into your Java Spring Boot application.

No official SDK is required to integrate Logto with your Java Spring Boot application. We will use the [Spring Security](https://spring.io/projects/spring-security) and [Spring Security OAuth2](https://spring.io/guides/tutorials/spring-boot-oauth2) libraries to handle the OIDC authentication flow with Logto.

Before we begin, make sure you have went through the spring boot guides linked above.

</Step>

<Step title="Add dependencies">
  Include the following dependencies in your `build.gradle` file:

```groovy title="build.gradle"
dependencies {
  implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
  implementation 'org.springframework.boot:spring-boot-starter-web'
  implementation 'org.springframework.boot:spring-boot-starter-security'
  implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
}
```

Our sample project uses [gradle](https://spring.io/guides/gs/gradle) as the build tool. You can use
maven or any other build tool as well. The configurations might be slightly different.

For maven, include the following dependencies in your `pom.xml` file:

```xml title="pom.xml"
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
```

</Step>

<Step title="Configure Logto OAuth2 Client registration">
  
Register your application with Logto to get the client credentials and IdP configurations.
Add the following configuration to your `application.properties` file:

<Code className="language-properties" title="application.properties">
    {`spring.security.oauth2.client.registration.logto.client-name=logto
spring.security.oauth2.client.registration.logto.client-id=${props.app.id}
spring.security.oauth2.client.registration.logto.client-secret=${props.secrets[0]?.value ?? props.app.secret}
spring.security.oauth2.client.registration.logto.redirect-uri={baseUrl}/login/oauth2/code/{registrationId}
spring.security.oauth2.client.registration.logto.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.logto.scope=openid,profile,email,offline_access
spring.security.oauth2.client.registration.logto.provider=logto

spring.security.oauth2.client.provider.logto.issuer-uri=${props.endpoint}oidc
spring.security.oauth2.client.provider.logto.authorization-uri=${props.endpoint}oidc/auth
spring.security.oauth2.client.provider.logto.jwk-set-uri=${props.endpoint}oidc/jwks
  `}
</Code>

<br/>

<CustomDomainEndpointNotice />

</Step>

<Step title="Setup the redirect URI in Logto">

<RedirectUrisWeb
  defaultBaseUrl="http://localhost:8080/"
  defaultRedirectUri="http://localhost:8080/login/oauth2/code/logto"
  defaultPostSignOutUri="http://localhost:8080/login/oauth2/code/logto"
/>

Make sure the redirect URI in Logto matches the `redirect-uri` set in the `application.properties` file in the previous step.

</Step>

<Step title="Implement the WebSecurityConfig">

The `WebSecurityConfig` class will be used to configure the security settings for your application. It is the key class that will handle the authentication and authorization flow. Please check the [Spring Security documentation](https://spring.io/guides/topicals/spring-security-architecture) for more details.

### Create a new class `WebSecurityConfig` in your project

```java title="WebSecurityConfig.java"
package com.example.securingweb;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

@Configuration
@EnableWebSecurity

public class WebSecurityConfig {
 // ...
}
```

### Create a idTokenDecoderFactory bean to set the JWS algorithm to `ES384`

This is required because Logto uses ES384 as the default algorithm, we need to update the OidcIdTokenDecoderFactory to use the same algorithm.

```java title="WebSecurityConfig.java"
import org.springframework.context.annotation.Bean;
import org.springframework.security.oauth2.client.oidc.authentication.OidcIdTokenDecoderFactory;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.security.oauth2.jwt.JwtDecoderFactory;

public class WebSecurityConfig {
  // ...

  @Bean
  public JwtDecoderFactory<ClientRegistration> idTokenDecoderFactory() {
    OidcIdTokenDecoderFactory idTokenDecoderFactory = new OidcIdTokenDecoderFactory();
    idTokenDecoderFactory.setJwsAlgorithmResolver(clientRegistration -> SignatureAlgorithm.ES384);
    return idTokenDecoderFactory;
  }
}
```

### Create a LoginSuccessHandler class to handle the login success event

Redirect the user to the user page after successful login:

```java title="LoginSuccessHandler.java"
package com.example.securingweb;

import java.io.IOException;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

public class CustomSuccessHandler implements AuthenticationSuccessHandler {
  @Override
  public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
      Authentication authentication) throws IOException, ServletException {
    response.sendRedirect("/user");
  }
}
```

### Create a LogoutSuccessHandler class to handle the logout success event

Clear the session and redirect the user to the home page.

```java title="LogoutSuccessHandler.java"
package com.example.securingweb;

import java.io.IOException;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

public class CustomLogoutHandler implements LogoutSuccessHandler {
  @Override
  public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
      throws IOException, ServletException {
    HttpSession session = request.getSession();

    if (session != null) {
      session.invalidate();
    }

    response.sendRedirect("/home");
  }
}
```

#### Create a `securityFilterChain` bean to configure the security configuration

Add the following code to complete the `WebSecurityConfig` class:

```java title="WebSecurityConfig.java"
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;

public class WebSecurityConfig {
  // ...

  @Bean
  public DefaultSecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
      .authorizeRequests(authorizeRequests ->
        authorizeRequests
          .antMatchers("/", "/home").permitAll() // Allow access to the home page
          .anyRequest().authenticated() // All other requests require authentication
      )
      .oauth2Login(oauth2Login ->
        oauth2Login
          .successHandler(new CustomSuccessHandler())
      )
      .logout(logout ->
        logout
          .logoutSuccessHandler(new CustomLogoutHandler())
      );
    return http.build();
  }
}
```

</Step>

<Step title="Create the home page" subtitle="Implement sign-in">

(You may skip this step if you already have a home page in your project)


```java title="HomeController.java"
package com.example.securingweb;

import java.security.Principal;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {
  @GetMapping({ "/", "/home" })
  public String home(Principal principal) {
    return principal != null ? "redirect:/user" : "home";
  }
}
```

This controller will redirect the user to the user page if the user is authenticated, otherwise, it will show the home page.

```html title="resources/templates/home.html"
<body>
  <h1>Welcome!</h1>

  <p><a th:href="@{/oauth2/authorization/logto}">Login with Logto</a></p>
</body>
```

</Step>

<Step title="Create the user page" subtitle="Implement sign-out">

Create a new controller to handle the user page:

```java title="UserController.java"
package com.example.securingweb;

import java.security.Principal;
import java.util.Map;

import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/user")
public class UserController {

  @GetMapping
  public String user(Model model, Principal principal) {
    if (principal instanceof OAuth2AuthenticationToken) {
      OAuth2AuthenticationToken token = (OAuth2AuthenticationToken) principal;
      OAuth2User oauth2User = token.getPrincipal();
      Map<String, Object> attributes = oauth2User.getAttributes();

      model.addAttribute("username", attributes.get("username"));
      model.addAttribute("email", attributes.get("email"));
      model.addAttribute("sub", attributes.get("sub"));
    }

    return "user";
  }
}
```

Read the user information from the `OAuth2User` object and pass it to the `user.html` template.

```html title="resources/templates/user.html"
<body>
  <h1>User Details</h1>
  <div>
    <p>
    <div><strong>name:</strong> <span th:text="${username}"></span></div>
    <div><strong>email:</strong> <span th:text="${email}"></span></div>
    <div><strong>id:</strong> <span th:text="${sub}"></span></div>
    </p>
  </div>

  <form th:action="@{/logout}" method="post">
    <input type="submit" value="Logout" />
  </form>
</body>
```

</Step>

<Step title="Checkpoint: Test your app">

<Checkpoint />

</Step>

</Steps>
