إعداد خادم الموارد
هيّئوا تطبيق Spring Boot ليعمل بوصفه خادم موارد OAuth2 لحماية نقاط نهاية واجهة API الخاصة به.
إعداد خادم الموارد درس مجاني في Spring Security 6 & JWT Authentication على CoddyKit. هذا هو الدرس 1 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Spring Security 6 & JWT Authentication، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Spring Security 6 & JWT Authentication 4 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
What is a Resource Server?
Welcome to configuring a Spring Security OAuth2 Resource Server! This is a crucial component in modern secure applications.
- A Resource Server hosts protected resources, like your API endpoints.
- It receives access tokens from clients and validates them.
- If a token is valid, it grants access to the requested resource.
Think of it as the bouncer at a club, checking tickets (access tokens) before letting anyone in.
Role in OAuth2 Flow
In the OAuth2 flow, the Resource Server works hand-in-hand with an Authorization Server.
- The client first gets an access token from the Authorization Server.
- Then, the client sends this token to the Resource Server when requesting a protected resource.
- The Resource Server doesn't issue tokens; it only validates them.
This separation of concerns makes your application more secure and scalable.
Essential Dependencies
To turn your Spring Boot application into an OAuth2 Resource Server, you need a specific dependency.
The key dependency is spring-boot-starter-oauth2-resource-server. This starter brings in all the necessary Spring Security components to handle OAuth2 access tokens.
It simplifies the setup process by providing auto-configuration for common scenarios.
Adding the Dependency
Let's add the required dependency to your project's pom.xml (for Maven users) or build.gradle (for Gradle users).
For Maven, place this inside your <dependencies> block:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>Enabling Resource Server Security
With the dependency in place, we need to configure Spring Security. In Spring Security 6, this is typically done using a SecurityFilterChain bean.
This configuration tells Spring Security to treat incoming requests as if they might contain an OAuth2 access token.
Basic Security Filter Chain
Here's a minimal Java configuration for enabling the Resource Server:
The oauth2ResourceServer().jwt() part tells Spring Security to expect JWTs (JSON Web Tokens) as access tokens.
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;
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2 -> oauth2.jwt());
return http.build();
}
}Configuring JWT Source
For the Resource Server to validate JWTs, it needs to know where to find the public keys or how to introspect the token.
You configure this in your application.properties or application.yml file. The most common way is to provide the JWK Set URI or the Issuer URI.
- JWK Set URI (
jwk-set-uri): Points to an endpoint where the Authorization Server publishes its public keys (JSON Web Key Set). - Issuer URI (
issuer-uri): Points to the Authorization Server's base URL, from which the JWK Set URI can be discovered.
Setting JWK Set URI
Let's add the jwk-set-uri to our application.properties. This URI is provided by your Authorization Server.
Replace http://auth-server/realms/master/protocol/openid-connect/certs with the actual URI from your Authorization Server.
spring.security.oauth2.resourceserver.jwt.jwk-set-uri=http://auth-server/realms/master/protocol/openid-connect/certsCreating a Protected Endpoint
Now, let's create a simple REST endpoint that our Resource Server will protect. Only requests with a valid access token will be able to reach this endpoint.
We'll use a basic @RestController for this.
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ProtectedController {
@GetMapping("/api/hello")
public String hello() {
return "Hello, secured world!";
}
}Putting It All Together
Here's a full, runnable Spring Boot application demonstrating a minimal Resource Server setup with a protected endpoint. Remember to update the jwk-set-uri in application.properties!
When you run this, try accessing /api/hello without a token (you'll get 401 Unauthorized).
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.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class ResourceServerApplication {
public static void main(String[] args) {
SpringApplication.run(ResourceServerApplication.class, args);
}
@Configuration
public static class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2 -> oauth2.jwt());
return http.build();
}
}
@RestController
public static class ProtectedController {
@GetMapping("/api/hello")
public String hello() {
return "Hello, secured world!";
}
}
}Resource Server Purpose Check
Which of the following best describes the primary role of an OAuth2 Resource Server?
Recap: Resource Server Setup
Great job! You've learned the fundamentals of setting up an OAuth2 Resource Server.
- We understood that a Resource Server protects APIs by validating access tokens.
- We added the
spring-boot-starter-oauth2-resource-serverdependency. - We configured a
SecurityFilterChainto enable JWT-based resource server security. - We learned how to specify the JWT source (e.g.,
jwk-set-uri) inapplication.properties.
Next, we'll dive deeper into how the Resource Server decodes and validates these JWTs.
الأسئلة الشائعة
هل درس «إعداد خادم الموارد» مجاني؟
نعم — نص درس «إعداد خادم الموارد» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Spring Security 6 & JWT Authentication، انتقل إلى CoddyKit PRO. تتضمن دورة Spring Security 6 & JWT Authentication 4 دروس في المجموع.
ماذا ستتعلم في «إعداد خادم الموارد»؟
هيّئوا تطبيق Spring Boot ليعمل بوصفه خادم موارد OAuth2 لحماية نقاط نهاية واجهة API الخاصة به. تتمرن على Spring Security 6 & JWT Authentication مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ Spring Security 6 & JWT Authentication؟
لا تُشترط خبرة سابقة. Spring Security 6 & JWT Authentication على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 1 من أصل 4.
كم من الوقت يستغرق درس «إعداد خادم الموارد»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس Spring Security 6 & JWT Authentication هذا؟
نعم. كل درس في Spring Security 6 & JWT Authentication يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- إعداد خادم الموارد
- فك ترميز رموز JWT والتحقق منها
- فرض النطاقات والمطالبات
- تعيين مطالب JWT إلى سلطات Spring