メインコンテンツへスキップ
前提条件:
  • JDK 17 以上 (ダウンロード)
  • Maven 3.6 以上、または Gradle 7 以上 (Maven | Gradle)
  • IDE (IntelliJ IDEA、Eclipse、または VS Code を推奨)
Java バージョンの互換性: Spring Boot 3.x 以降および Okta Spring Boot Starter 3.x では、Java 17 以降が必要です。

はじめに

このクイックスタートでは、Spring Boot の Web アプリケーションに Auth0 のログインを追加する方法を説明します。Okta Spring Boot Starter を使用して、ログイン、ログアウト、保護されたプロフィールページを備えた安全な Web アプリケーションを構築します。この Starter は、Spring Security の OAuth2 ログインサポートを自動的に設定します。
1

新規プロジェクトを作成する

必要な依存関係を含む Spring Boot プロジェクトを作成します。
curl -L https://start.spring.io/starter.zip \
    -d dependencies=web,security,thymeleaf \
    -d javaVersion=17 \
    -d name=auth0-webapp \
    -d artifactId=auth0-webapp \
    -d packageName=com.auth0.example \
    -o auth0-webapp.zip

mkdir auth0-webapp && unzip auth0-webapp.zip -d auth0-webapp && cd auth0-webapp
2

Okta Spring Boot Starterを追加する

Okta Spring Boot Starter の依存関係をプロジェクトに追加します。これにより、Auth0/Okta 向けの自動構成を備えた Spring Security OAuth2 ログインサポートが組み込まれます。
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<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.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity6</artifactId>
</dependency>
<dependency>
    <groupId>com.okta.spring</groupId>
    <artifactId>okta-spring-boot-starter</artifactId>
    <version>3.1.0</version>
</dependency>
3

Auth0 を設定する

Auth0テナントでRegular Web Applicationを作成し、プロジェクトに設定を追加してください。CLIコマンドを実行して自動的に行う方法と、Dashboardから手動で行う方法のいずれかを選択できます。
Auth0 アプリケーションを作成して application.yml ファイルを更新するには、プロジェクトのルートディレクトリで次のシェルコマンドを実行します。
AUTH0_APP_NAME="My Spring Boot Webapp" && \
brew tap auth0/auth0-cli && \
brew install auth0 && \
auth0 login --no-input && \
auth0 apps create -n "${AUTH0_APP_NAME}" -t regular \
    --callbacks "http://localhost:3000/login/oauth2/code/okta" \
    --logout-urls "http://localhost:3000/" \
    --json > auth0-app-details.json && \
DOMAIN=$(auth0 tenants list --json | jq -r '.[] | select(.active == true) | .name') && \
CLIENT_ID=$(jq -r '.client_id' auth0-app-details.json) && \
CLIENT_SECRET=$(jq -r '.client_secret' auth0-app-details.json) && \
mkdir -p src/main/resources && \
printf 'server:\n  port: 3000\n\nokta:\n  oauth2:\n    issuer: https://%s/\n    client-id: %s\n    client-secret: %s\n' "$DOMAIN" "$CLIENT_ID" "$CLIENT_SECRET" > src/main/resources/application.yml && \
rm auth0-app-details.json && \
echo "✅ application.yml created with your Auth0 app details:" && \
cat src/main/resources/application.yml
4

認証を設定

OAuth2 ログインを有効にし、Auth0 からのログアウトを処理するセキュリティ設定を作成します。認証されていないユーザーは自動的に Auth0 のログインページにリダイレクトされます。
// src/main/java/com/auth0/example/SecurityConfig.java

package com.auth0.example;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.io.IOException;

import static org.springframework.security.config.Customizer.withDefaults;

@Configuration
public class SecurityConfig {

    @Value("${okta.oauth2.issuer}")
    private String issuer;
    @Value("${okta.oauth2.client-id}")
    private String clientId;

    @Bean
    public SecurityFilterChain configure(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(authorize -> authorize
                .requestMatchers("/", "/images/**").permitAll()
                .anyRequest().authenticated()
            )
            .oauth2Login(withDefaults())
            .logout(logout -> logout
                .addLogoutHandler(logoutHandler()));
        return http.build();
    }

    private LogoutHandler logoutHandler() {
        return (request, response, authentication) -> {
            try {
                String baseUrl = ServletUriComponentsBuilder.fromCurrentContextPath().build().toUriString();
                response.sendRedirect(issuer + "v2/logout?client_id=" + clientId + "&returnTo=" + baseUrl);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        };
    }
}
5

コントローラーとビューを作成する

ホームページとプロフィールページ用のコントローラーと Thymeleaf テンプレートを作成します。
6

アプリケーションを実行する

Maven または Gradle のラッパーを使用して、アプリケーションを起動します。
./mvnw spring-boot:run
アプリケーションは http://localhost:3000 で実行中です。Auth0 のログインフローを開始するには、http://localhost:3000/profile にアクセスします。
これで、Auth0 ログインを備えた完全に動作する Spring Boot Web アプリケーションが localhost で実行されているはずです。ホームページは公開されており、/profile にアクセスすると、未認証のユーザーは Auth0 のログインページにリダイレクトされます。

高度な使い方

@AuthenticationPrincipal OidcUser パラメーターを使用すると、IDトークンのすべてのクレームにアクセスできます。すべてのクレームを取得するには getClaims() を使用し、特定のクレームを取得するには個別の getter メソッドを使用します。
@GetMapping("/profile")
public String profile(Model model, @AuthenticationPrincipal OidcUser oidcUser) {
    model.addAttribute("name", oidcUser.getFullName());
    model.addAttribute("email", oidcUser.getEmail());
    model.addAttribute("picture", oidcUser.getPicture());
    model.addAttribute("sub", oidcUser.getSubject());
    model.addAttribute("allClaims", oidcUser.getClaims());
    return "profile";
}
Auth0 のロールに基づいてページへのアクセスを制限できます。まず、Auth0のActionを使用して IDトークンにロールを追加し、その後セキュリティ設定で hasAuthority() を使用します。

トークンにロールを追加する

  1. Auth0 DashboardActionsFlowsLogin に移動します。
  2. IDトークンにカスタムクレームとしてロールを追加するカスタム Action を作成します。
exports.onExecutePostLogin = async (event, api) => {
  const namespace = "https://my-app.example.com";
  if (event.authorization) {
    api.idToken.setCustomClaim(`${namespace}/roles`, event.authorization.roles);
  }
};

認可を設定する

エンドポイントで特定のロールを必須にするよう、SecurityConfig を更新します。
@Bean
public SecurityFilterChain configure(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(authorize -> authorize
            .requestMatchers("/", "/images/**").permitAll()
            .requestMatchers("/admin/**").hasAuthority("ROLE_admin")
            .anyRequest().authenticated()
        )
        .oauth2Login(withDefaults())
        .logout(logout -> logout
            .addLogoutHandler(logoutHandler()));
    return http.build();
}
Okta Starter は、AuthoritiesProvider インターフェイスを介したカスタム権限マッピングをサポートしています。ユーザー属性や外部データソースに基づいてカスタム GrantedAuthority オブジェクトを追加するには、Bean を登録します。
package com.auth0.example;

import com.okta.spring.boot.oauth.AuthoritiesProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Configuration
public class AuthoritiesConfig {

    @Bean
    AuthoritiesProvider customAuthoritiesProvider() {
        return (user, userRequest) -> {
            Set<GrantedAuthority> authorities = new HashSet<>();

            // カスタム roles クレームを Spring Security の権限にマッピングする
            Object roles = user.getAttribute("https://my-app.example.com/roles");
            if (roles instanceof List<?> roleList) {
                roleList.forEach(role ->
                    authorities.add(new SimpleGrantedAuthority("ROLE_" + role))
                );
            }

            return authorities;
        };
    }
}

よくある問題

ログインを選択すると、Auth0 にコールバック URL の不一致に関するエラーが表示されます。Auth0 アプリケーションの Allowed Callback URLs は、Spring Security で使用されるコールバック URL と完全に一致している必要があります。デフォルトは http://localhost:3000/login/oauth2/code/okta です。
  1. Auth0 DashboardApplications → Your App → Settings に移動します。
  2. Allowed Callback URLshttp://localhost:3000/login/oauth2/code/okta を追加します。
  3. Save Changes を選択します。
アプリケーションの起動に失敗するか、issuer の不一致によりログインに失敗します。okta.oauth2.issuer には、https:// と末尾の / を含む完全な Auth0 テナント URL を指定する必要があります。
# ❌ 誤り - https:// または末尾のスラッシュがない
okta:
  oauth2:
    issuer: "dev-abc123.us.auth0.com"

# ✅ 正しい - 末尾のスラッシュを含む完全な URL
okta:
  oauth2:
    issuer: "https://dev-abc123.us.auth0.com/"
/.well-known/openid-configuration の取得時に接続エラーが発生し、アプリケーションの起動に失敗します。Okta Spring Boot Starter は、起動時に issuer URL から OpenID Connect ディスカバリードキュメントを取得します。issuer URL が正しく、ネットワークから到達可能であることを確認してください。社内ファイアウォールの内側にある場合は、プロキシを設定してください。
okta:
  oauth2:
    issuer: "https://dev-abc123.us.auth0.com/"
    proxy:
      host: "proxy.example.com"
      port: 8080
アプリケーションは起動しますが、設定プロパティが読み込まれていないため、ログインに失敗します。application.yml で、okta.oauth2 名前空間の下に正しい YAML のインデントが使われていることを確認してください。
# ❌ 誤り - フラットな構造で、ネストされていない
okta.oauth2.issuer: "https://dev-abc123.us.auth0.com/"

# ✅ 正しい - 適切にネストされた YAML
okta:
  oauth2:
    issuer: "https://dev-abc123.us.auth0.com/"
    client-id: "YOUR_CLIENT_ID"
    client-secret: "YOUR_CLIENT_SECRET"
ログアウトを選択した後、Auth0 のログインページが表示されず、ユーザーはすぐに再ログインした状態になります。SecurityConfig に、Auth0 の /v2/logout エンドポイントへリダイレクトするカスタム LogoutHandler が含まれていることを確認してください。また、Auth0 アプリケーション設定の Allowed Logout URLshttp://localhost:3000/ が含まれていることも確認してください。

参考資料

SDKドキュメント

SDKの完全なドキュメント、ソースコード、リリースノート

Auth0ドキュメント

Spring Bootアプリケーション向けのAuth0公式ドキュメント

Spring Securityリファレンス

Spring Security OAuth2 Loginのドキュメント

設定リファレンス

使用可能なすべてのokta.oauth2.*設定プロパティ

Auth0 Dashboard

Auth0のAPIとアプリケーションを管理します

コミュニティフォーラム

Auth0コミュニティからサポートを受ける

サンプルアプリケーション

Auth0 を使用したログイン、プロフィール表示、ログアウトを実装した完全なサンプルアプリケーションは、Auth0 サンプルリポジトリで公開されています。

MVC ログインサンプル

Auth0 OAuth2 統合によるログイン、ログアウト、プロフィールページが含まれています
クローンして実行します。
git clone https://github.com/auth0-samples/auth0-spring-boot-login-samples.git
cd auth0-spring-boot-login-samples/mvc-login

# Auth0の設定でsrc/main/resources/application.ymlを更新してください
# 次に実行してください:
./gradlew bootRun
ブラウザーで http://localhost:3000 を開き、ログイン リンクを選択して Auth0 のログインフローをテストします。