Skillpedia
واجهات API والخوادم (backend)280k · #246

springboot-security

ما الذي تفعله

تساعد هذه المهارة على حماية تطبيق الويب المكتوب بلغة Java (Spring Boot). تضمن ألا يصل إلى المعلومات الحساسة إلا المستخدمون المصرح لهم، وتمنع الهجمات الشائعة مثل حقن الكود وسرقة البيانات.

متى تستخدمها

  • ✓عندما تضيف تسجيل الدخول وكلمات المرور إلى تطبيقك.
  • ✓عندما تضبط من يمكنه رؤية أو فعل ماذا في تطبيقك.
  • ✓عندما تحمي تطبيقك من المخترقين وسرقة البيانات.

رابط المهارة

https://github.com/affaan-m/ECC/blob/main/pi/core/skills/springboot-security/SKILL.md

انسخه والصقه في الذكاء الاصطناعي الذي تستخدمه (Claude أو ChatGPT أو Cursor) واطلب منه اتباع التعليمات.

طريقة الاستخدام

أسهل طريقة: انسخ الرسالة والصقها في الذكاء الاصطناعي الذي تستخدمه. سيقرأ المهارة وينفّذ تعليماتها.

رسالة جاهزة للصق

استخدم هذه المهارة لمساعدتي: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/springboot-security/SKILL.md اقرأ ملف SKILL.md في هذا الرابط ونفّذ تعليماته لمهمتي.
تريد أن يجد الذكاء الاصطناعي مهارات مثل هذه بنفسه؟ثبّت خادم Skillpedia MCP المجاني: سطر واحد، ويبحث في 15,000+ مهارة قبل كل مهمة.ثبّته في دقيقة واحدة →

مثال على ما تطلبه من الذكاء الاصطناعي

“كيف أحمي تطبيقي من الوصول غير المصرح به؟”

5 مهارات جديدة كل أسبوع. قراءة في دقيقة واحدة.

كيف تعمل

تضبط هذه المهارة قواعد الأمان، مثل من يستطيع الوصول إلى أي جزء من تطبيقك. كما تتحقق من المعلومات التي يرسلها المستخدمون، وتحمي من الكود الخبيث.

المحتوى التقني (ملف SKILL.md الأصلي)

النص الأصلي من المؤلف، مباشرة من GitHub.

Spring Boot Security Review

Use when adding auth, handling input, creating endpoints, or dealing with secrets.

When to Activate

  • Adding authentication (JWT, OAuth2, session-based)
  • Implementing authorization (@PreAuthorize, role-based access)
  • Validating user input (Bean Validation, custom validators)
  • Configuring CORS, CSRF, or security headers
  • Managing secrets (Vault, environment variables)
  • Adding rate limiting or brute-force protection
  • Scanning dependencies for CVEs

Authentication

  • Prefer stateless JWT or opaque tokens with revocation list
  • Use httpOnly, Secure, SameSite=Strict cookies for sessions
  • Validate tokens with OncePerRequestFilter or resource server
@Component
public class JwtAuthFilter extends OncePerRequestFilter {
  private final JwtService jwtService;

  public JwtAuthFilter(JwtService jwtService) {
    this.jwtService = jwtService;
  }

  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
      FilterChain chain) throws ServletException, IOException {
    String header = request.getHeader(HttpHeaders.AUTHORIZATION);
    if (header != null && header.startsWith("Bearer ")) {
      String token = header.substring(7);
      Authentication auth = jwtService.authenticate(token);
      SecurityContextHolder.getContext().setAuthentication(auth);
    }
    chain.doFilter(request, response);
  }
}

Authorization

  • Enable method security: @EnableMethodSecurity
  • Use @PreAuthorize("hasRole('ADMIN')") or @PreAuthorize("@authz.canEdit(#id)")
  • Deny by default; expose only required scopes
@RestController
@RequestMapping("/api/admin")
public class AdminController {

  @PreAuthorize("hasRole('ADMIN')")
  @GetMapping("/users")
  public List<UserDto> listUsers() {
    return userService.findAll();
  }

  @PreAuthorize("@authz.isOwner(#id, authentication)")
  @DeleteMapping("/users/{id}")
  public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
    userService.delete(id);
    return ResponseEntity.noContent().build();
  }
}

Input Validation

  • Use Bean Validation with @Valid on controllers
  • Apply constraints on DTOs: @NotBlank, @Email, @Size, custom validators
  • Sanitize any HTML with a whitelist before rendering
// BAD: No validation
@PostMapping("/users")
public User createUser(@RequestBody UserDto dto) {
  return userService.create(dto);
}

// GOOD: Validated DTO
public record CreateUserDto(
    @NotBlank @Size(max = 100) String name,
    @NotBlank @Email String email,
    @NotNull @Min(0) @Max(150) Integer age
) {}

@PostMapping("/users")
public ResponseEntity<UserDto> createUser(@Valid @RequestBody CreateUserDto dto) {
  return ResponseEntity.status(HttpStatus.CREATED)
      .body(userService.create(dto));
}

SQL Injection Prevention

  • Use Spring Data repositories or parameterized queries
  • For native queries, use :param bindings; never concatenate strings
// BAD: String concatenation in native query
@Query(value = "SELECT * FROM users WHERE name = '" + name + "'", nativeQuery = true)

// GOOD: Parameterized native query
@Query(value = "SELECT * FROM users WHERE name = :name", nativeQuery = true)
List<User> findByName(@Param("name") String name);

// GOOD: Spring Data derived query (auto-parameterized)
List<User> findByEmailAndActiveTrue(String email);

Password Encoding

  • Always hash passwords with BCrypt or Argon2 — never store plaintext
  • Use PasswordEncoder bean, not manual hashing
@Bean
public PasswordEncoder passwordEncoder() {
  return new BCryptPasswordEncoder(12); // cost factor 12
}

// In service
public User register(CreateUserDto dto) {
  String hashedPassword = passwordEncoder.encode(dto.password());
  return userRepository.save(new User(dto.email(), hashedPassword));
}

CSRF Protection

  • For browser session apps, keep CSRF enabled; include token in forms/headers
  • For pure APIs with Bearer tokens, disable CSRF and rely on stateless auth
http
  .csrf(csrf -> csrf.disable())
  .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

Secrets Management

  • No secrets in source; load from env or vault
  • Keep application.yml free of credentials; use placeholders
  • Rotate tokens and DB credentials regularly
# BAD: Hardcoded in application.yml
spring:
  datasource:
    password: mySecretPassword123

# GOOD: Environment variable placeholder
spring:

…
الأسئلة الشائعة

ما هي المصادقة (authentication)؟

هي عملية التحقق من هويتك، عادةً باسم المستخدم وكلمة المرور.

ما هو التفويض (authorization)؟

هو تحديد ما يستطيع المستخدم الذي تمت مصادقته أن يفعله أو يراه.

لماذا لا أضع كلمات المرور مباشرة في الكود؟

لأن كلمات المرور في الكود خطرة، فأي شخص يرى الكود يستطيع معرفتها. الأفضل استخدام طرق أكثر أمانًا لتخزين الأسرار.

التفاصيل

الوصف الأصلي من المؤلف

Spring Security best practices for authn/authz, validation, CSRF, secrets, headers, rate limiting, and dependency security in Java Spring Boot services. Use when reviewing Spring Security authn/authz, validation, CSRF, secrets, headers, or rate limiting.

repo: affaan-m/ECC

الشعبية

نجوم GitHub
280k
الترتيب
#246
الترخيص
MIT
آخر تحديث
15‏/10‏/2026

هل هذه المهارة مفيدة؟

0

سجّل الدخول للتصويت.

التعليقات

  • …

المزيد من المهارات من هذا المستودع

مهارات مشابهة