0Pricing
Spring Security 6 & JWT Authentication · 课时

作用域和声明的强制执行

强制要求传入 JWT 包含特定作用域和声明,以控制对 API 不同部分的访问。

作用域和声明的强制执行 是 CoddyKit 上的免费 Spring Security 6 & JWT Authentication 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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!

常见问题解答

「作用域和声明的强制执行」课时是免费的吗?

是的 — 「作用域和声明的强制执行」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Spring Security 6 & JWT Authentication 课程的其余内容,请升级到 CoddyKit PRO。 Spring Security 6 & JWT Authentication 课程共包含 4 节课。

「作用域和声明的强制执行」这节课中我会学到什么?

强制要求传入 JWT 包含特定作用域和声明,以控制对 API 不同部分的访问。 你通过在浏览器中直接运行的动手代码来练习 Spring Security 6 & JWT Authentication,全天候 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 权限
← 返回 Spring Security 6 & JWT Authentication