0Pricing
Spring Security 6 & JWT Authentication · レッスン

スコープとクレームの適用

受信したJWT内の特定のスコープとクレームを適用し、APIの各部分へのアクセスを制御します。

「スコープとクレームの適用」はCoddyKit上の無料Spring Security 6 & JWT Authenticationレッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはSpring Security 6 & JWT Authentication学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Spring Security 6 & JWT Authenticationコースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

Authorization with Scopes & Claims

Welcome! In this lesson, we'll learn how to control access to your API endpoints using scopes and claims in an OAuth2 Resource Server.

These are crucial components of a JSON Web Token (JWT) that tell your server who the user is and what they are allowed to do.

Understanding OAuth2 Scopes

Think of scopes as specific permissions or access rights that a client application requests on behalf of a user.

  • They are defined by the Resource Server.
  • Examples: read, write, profile, email.
  • When a user grants permission, these scopes are included in the issued JWT.

They define the "what" a client can do within the API.

JWT Claims Explained

Claims are pieces of information about the user or the token itself, stored as key-value pairs inside the JWT payload.

  • Standard Claims: sub (subject/user ID), exp (expiration time), iss (issuer).
  • Custom Claims: You can add your own data, like role, department, or user_id.

Claims provide context about "who" the user is and their specific attributes.

Spring Security & Scopes Mapping

When Spring Security processes an incoming JWT, it automatically extracts the scopes from the token.

It then converts these scopes into Spring Security authorities by prefixing them with SCOPE_.

For example, a scope read becomes an authority SCOPE_read, which can then be checked using expression language.

@PreAuthorize for Scopes

You can enforce scope-based authorization on your API methods using Spring Security's @PreAuthorize annotation.

This annotation allows you to define SpEL (Spring Expression Language) expressions that must evaluate to true for the method to be executed.

Use hasAuthority('SCOPE_<your_scope>') to check for a specific scope.

Scope Protection Demo

Let's see how to protect an endpoint using the SCOPE_read authority. Only tokens with the 'read' scope can access this resource.

package com.coddykit.security;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.security.access.prepost.PreAuthorize;

@SpringBootApplication
@EnableMethodSecurity // Enable @PreAuthorize
public class Main {
  public static void main(String[] args) {
    SpringApplication.run(Main.class, args);
  }
}

@Configuration
class SecurityConfig {
  @Bean
  SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
      .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
      .oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> {}))
      .csrf(csrf -> csrf.disable()); // For simplicity in demo
    return http.build();
  }
}

@RestController
class DataController {
  @GetMapping("/data/public")
  public String getPublicData() {
    return "This is public data (authenticated)";
  }

  @GetMapping("/data/secret")
  @PreAuthorize("hasAuthority('SCOPE_read')")
  public String getSecretData() {
    return "This is secret data, requires 'read' scope!";
  }
}

Leveraging Custom Claims

While scopes are great for general permissions, custom claims allow for more fine-grained or context-specific authorization.

For example, you might have a role claim with values like ADMIN or USER, or a department_id claim.

These claims are directly accessible from the authenticated principal in Spring Security, offering rich contextual data.

@PreAuthorize for Claims

You can also use @PreAuthorize to check for specific claims in the JWT payload.

Spring Security's SpEL allows you to access the authenticated principal's claims directly.

Use expressions like #oauth2.token.claims['role'] == 'ADMIN' or #oauth2.token.claims['department'] == 'IT'.

Claim Protection Demo

Here's an example of an endpoint protected by a custom role claim. Only users with role:ADMIN can access this sensitive data.

package com.coddykit.security;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.security.access.prepost.PreAuthorize;

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

@Configuration
class SecurityConfig {
  @Bean
  SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
      .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
      .oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> {}))
      .csrf(csrf -> csrf.disable());
    return http.build();
  }
}

@RestController
class AdminController {
  @GetMapping("/admin/report")
  @PreAuthorize("#oauth2.token.claims['role'] == 'ADMIN'")
  public String getAdminReport() {
    return "Sensitive admin report data!";
  }

  @GetMapping("/admin/dashboard")
  @PreAuthorize("hasAuthority('SCOPE_admin') and #oauth2.token.claims['department'] == 'IT'")
  public String getITAdminDashboard() {
    return "IT Department Admin Dashboard!";
  }
}

Quick Check: Scopes & Claims

Which of the following statements correctly describe the use of scopes and claims in Spring Security for an OAuth2 Resource Server?

Recap: Scopes & Claims

We've covered how scopes and claims are fundamental for authorization in an OAuth2 Resource Server.

  • Scopes define broad permissions (e.g., read, write).
  • Claims provide detailed user attributes (e.g., role, department).
  • Both can be enforced using @PreAuthorize with SpEL expressions.

Mastering these allows for robust and flexible access control in your APIs!

よくある質問

「スコープとクレームの適用」レッスンは無料ですか?

はい。「スコープとクレームの適用」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Spring Security 6 & JWT Authenticationコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Spring Security 6 & JWT Authenticationコースには全4レッスンが含まれています。

「スコープとクレームの適用」で何を学びますか?

受信したJWT内の特定のスコープとクレームを適用し、APIの各部分へのアクセスを制御します。 ブラウザで直接実行するハンズオンコードでSpring Security 6 & JWT Authenticationを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Spring Security 6 & JWT Authenticationを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのSpring Security 6 & JWT Authenticationは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン3/4です。

「スコープとクレームの適用」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このSpring Security 6 & JWT Authenticationレッスンでコードを書いて実行できますか?

はい。すべてのSpring Security 6 & JWT Authenticationレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. リソースサーバーのセットアップ
  2. JWTのデコードと検証
  3. スコープとクレームの適用
  4. JWTクレームをSpring Authoritiesにマッピングする
← Spring Security 6 & JWT Authenticationに戻る