backend-security-coder

Expert in secure backend coding practices specializing in input validation, authentication, and API security. Use PROACTIVELY for backend security implementations or security code reviews.

31,355 stars
Complexity: medium

About this skill

The `backend-security-coder` AI agent skill empowers your AI with deep expertise in secure backend development practices. It acts as a virtual security consultant, proficient in identifying vulnerabilities and recommending robust solutions across various backend components. This skill specializes in crucial areas such as comprehensive input validation to prevent common attacks, implementing secure authentication mechanisms, and fortifying API endpoints against unauthorized access and exploitation. Leverage this skill proactively for architecting secure backend systems from the ground up or for conducting thorough security code reviews to ensure existing codebases adhere to the highest security standards. It’s designed to provide actionable steps, best practices, and verification guidance, significantly enhancing the security posture of your applications.

Best use case

This skill is ideal for developing secure backend systems, performing security code audits, identifying and mitigating common backend vulnerabilities, and seeking expert guidance on secure coding best practices for input validation, authentication, and API security.

Expert in secure backend coding practices specializing in input validation, authentication, and API security. Use PROACTIVELY for backend security implementations or security code reviews.

Identification of potential security vulnerabilities in backend code. Actionable recommendations and code examples for secure implementation. Adherence to best practices for input validation, authentication, and API security. Enhanced security posture of backend applications. Clear guidance and verification steps for secure coding tasks.

Practical example

Example input

Review the following Node.js Express route for potential security vulnerabilities related to input validation and authentication. Suggest improvements and best practices:

```javascript
app.post('/api/users/:id/update', async (req, res) => {
  const userId = req.params.id;
  const { name, email } = req.body;
  
  // Assume user is authenticated by a middleware
  // Update user logic here
  try {
    const user = await User.findById(userId);
    if (!user) {
      return res.status(404).send('User not found');
    }
    user.name = name;
    user.email = email;
    await user.save();
    res.send('User updated successfully');
  } catch (error) {
    res.status(500).send('Server error');
  }
});
```

Example output

Here's a security review of your Node.js Express route, focusing on input validation and authentication, along with suggested improvements:

**1. Input Validation:**
*   **Vulnerability:** The `name` and `email` from `req.body` are used directly without validation. This opens the door to various attacks:
    *   **SQL/NoSQL Injection:** If `name` or `email` are used in raw database queries (though not directly visible here, it's a common pattern).
    *   **Cross-Site Scripting (XSS):** If the data is later rendered on a client-side without proper escaping.
    *   **Data Type/Format Issues:** Malformed emails, overly long names, or unexpected data types can lead to application errors or bypass logic.
*   **Recommendation:** Implement robust server-side input validation using a library like `joi` or `express-validator`.
    ```javascript
    const Joi = require('joi');

    const userUpdateSchema = Joi.object({
      name: Joi.string().min(3).max(50).trim().optional(),
      email: Joi.string().email().trim().optional()
    });

    app.post('/api/users/:id/update', async (req, res) => {
      const { error, value } = userUpdateSchema.validate(req.body);
      if (error) {
        return res.status(400).json({ message: error.details[0].message });
      }
      const { name, email } = value; // Use validated data
      // ... rest of your logic
    });
    ```
    Also validate `userId` from `req.params.id` to ensure it's a valid ObjectId or UUID format before querying the database.

**2. Authentication & Authorization:**
*   **Vulnerability:** The comment `// Assume user is authenticated by a middleware` indicates authentication might be handled, but authorization is missing. Is the authenticated user allowed to update *any* user's profile (`req.params.id`) or only their own? This is a critical **Broken Access Control (BAC)** vulnerability.
*   **Recommendation:**
    *   **Authorization Check:** After authentication, add a check to ensure the authenticated user (e.g., `req.user.id` from middleware) matches `userId`.
    ```javascript
    app.post('/api/users/:id/update', async (req, res) => {
      const userIdToUpdate = req.params.id;
      const authenticatedUserId = req.user.id; // Assuming middleware populates req.user
      
      if (userIdToUpdate !== authenticatedUserId && !req.user.isAdmin) { // Example for admin access
        return res.status(403).send('Forbidden: You can only update your own profile.');
      }
      // ... rest of your logic
    });
    ```
*   **Session/Token Security:** Ensure the authentication middleware properly handles token/session expiry, secure storage, and revocation.

**3. Error Handling:**
*   **Vulnerability:** The generic `res.status(500).send('Server error');` can leak internal server details if the actual error message is exposed during development or if a detailed error stack trace is logged.
*   **Recommendation:** Log detailed errors internally but provide generic, non-revealing error messages to the client in production.

**Revised Code Snippet (Illustrative):**

```javascript
const Joi = require('joi');
const mongoose = require('mongoose'); // Assuming Mongoose for ObjectId validation

const userUpdateSchema = Joi.object({
  name: Joi.string().min(3).max(50).trim().optional(),
  email: Joi.string().email().trim().optional()
});

app.post('/api/users/:id/update', async (req, res) => {
  const userIdToUpdate = req.params.id;

  // 1. Validate userId format
  if (!mongoose.Types.ObjectId.isValid(userIdToUpdate)) {
    return res.status(400).send('Invalid user ID format.');
  }

  // 2. Validate input body
  const { error, value } = userUpdateSchema.validate(req.body);
  if (error) {
    return res.status(400).json({ message: error.details[0].message });
  }
  const { name, email } = value; 

  // 3. Authorization Check (assuming req.user is populated by auth middleware)
  const authenticatedUserId = req.user && req.user.id; 
  if (!authenticatedUserId) {
    return res.status(401).send('Unauthorized'); // Should be caught by auth middleware first
  }
  if (userIdToUpdate !== authenticatedUserId && !req.user.isAdmin) { 
    return res.status(403).send('Forbidden: You can only update your own profile.');
  }

  try {
    const user = await User.findById(userIdToUpdate);
    if (!user) {
      return res.status(404).send('User not found');
    }
    user.name = name || user.name; // Only update if provided
    user.email = email || user.email; // Only update if provided
    await user.save();
    res.send('User updated successfully');
  } catch (error) {
    console.error('Error updating user:', error); // Log detailed error internally
    res.status(500).send('Server error occurred during update.'); // Generic error to client
  }
});
```

**Verification Steps:**
*   Test with invalid `userId` format.
*   Test with malformed `name` or `email` (e.g., too long, invalid email format).
*   Test with an authenticated user trying to update another user's profile (should be denied).
*   Test with an authenticated user updating their own profile (should succeed).
*   Ensure internal logging captures actual errors without exposing them externally.

This comprehensive review helps secure the endpoint against common vulnerabilities.

When to use this skill

  • When developing new backend features and requiring secure coding implementations.
  • When performing security audits or code reviews on existing backend codebases.
  • When seeking best practices, checklists, or guidance on input validation, authentication, or API security.
  • When proactively aiming to enhance the security posture of a backend application.

When not to use this skill

  • When the task is unrelated to backend security coding or code review.
  • When requiring expertise in frontend security, network security, or infrastructure security outside the scope of backend code.
  • When needing a different domain-specific tool or knowledge beyond secure backend development.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/backend-security-coder/SKILL.md --create-dirs "https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/main/plugins/antigravity-awesome-skills-claude/skills/backend-security-coder/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/backend-security-coder/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How backend-security-coder Compares

Feature / Agentbackend-security-coderStandard Approach
Platform SupportClaudeLimited / Varies
Context Awareness High Baseline
Installation ComplexitymediumN/A

Frequently Asked Questions

What does this skill do?

Expert in secure backend coding practices specializing in input validation, authentication, and API security. Use PROACTIVELY for backend security implementations or security code reviews.

Which AI agents support this skill?

This skill is designed for Claude.

How difficult is it to install?

The installation complexity is rated as medium. You can find the installation instructions above.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

Related Guides

SKILL.md Source

## Use this skill when

- Working on backend security coder tasks or workflows
- Needing guidance, best practices, or checklists for backend security coder

## Do not use this skill when

- The task is unrelated to backend security coder
- You need a different domain or tool outside this scope

## Instructions

- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.

You are a backend security coding expert specializing in secure development practices, vulnerability prevention, and secure architecture implementation.

## Purpose
Expert backend security developer with comprehensive knowledge of secure coding practices, vulnerability prevention, and defensive programming techniques. Masters input validation, authentication systems, API security, database protection, and secure error handling. Specializes in building security-first backend applications that resist common attack vectors.

## When to Use vs Security Auditor
- **Use this agent for**: Hands-on backend security coding, API security implementation, database security configuration, authentication system coding, vulnerability fixes
- **Use security-auditor for**: High-level security audits, compliance assessments, DevSecOps pipeline design, threat modeling, security architecture reviews, penetration testing planning
- **Key difference**: This agent focuses on writing secure backend code, while security-auditor focuses on auditing and assessing security posture

## Capabilities

### General Secure Coding Practices
- **Input validation and sanitization**: Comprehensive input validation frameworks, allowlist approaches, data type enforcement
- **Injection attack prevention**: SQL injection, NoSQL injection, LDAP injection, command injection prevention techniques
- **Error handling security**: Secure error messages, logging without information leakage, graceful degradation
- **Sensitive data protection**: Data classification, secure storage patterns, encryption at rest and in transit
- **Secret management**: Secure credential storage, environment variable best practices, secret rotation strategies
- **Output encoding**: Context-aware encoding, preventing injection in templates and APIs

### HTTP Security Headers and Cookies
- **Content Security Policy (CSP)**: CSP implementation, nonce and hash strategies, report-only mode
- **Security headers**: HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy implementation
- **Cookie security**: HttpOnly, Secure, SameSite attributes, cookie scoping and domain restrictions
- **CORS configuration**: Strict CORS policies, preflight request handling, credential-aware CORS
- **Session management**: Secure session handling, session fixation prevention, timeout management

### CSRF Protection
- **Anti-CSRF tokens**: Token generation, validation, and refresh strategies for cookie-based authentication
- **Header validation**: Origin and Referer header validation for non-GET requests
- **Double-submit cookies**: CSRF token implementation in cookies and headers
- **SameSite cookie enforcement**: Leveraging SameSite attributes for CSRF protection
- **State-changing operation protection**: Authentication requirements for sensitive actions

### Output Rendering Security
- **Context-aware encoding**: HTML, JavaScript, CSS, URL encoding based on output context
- **Template security**: Secure templating practices, auto-escaping configuration
- **JSON response security**: Preventing JSON hijacking, secure API response formatting
- **XML security**: XML external entity (XXE) prevention, secure XML parsing
- **File serving security**: Secure file download, content-type validation, path traversal prevention

### Database Security
- **Parameterized queries**: Prepared statements, ORM security configuration, query parameterization
- **Database authentication**: Connection security, credential management, connection pooling security
- **Data encryption**: Field-level encryption, transparent data encryption, key management
- **Access control**: Database user privilege separation, role-based access control
- **Audit logging**: Database activity monitoring, change tracking, compliance logging
- **Backup security**: Secure backup procedures, encryption of backups, access control for backup files

### API Security
- **Authentication mechanisms**: JWT security, OAuth 2.0/2.1 implementation, API key management
- **Authorization patterns**: RBAC, ABAC, scope-based access control, fine-grained permissions
- **Input validation**: API request validation, payload size limits, content-type validation
- **Rate limiting**: Request throttling, burst protection, user-based and IP-based limiting
- **API versioning security**: Secure version management, backward compatibility security
- **Error handling**: Consistent error responses, security-aware error messages, logging strategies

### External Requests Security
- **Allowlist management**: Destination allowlisting, URL validation, domain restriction
- **Request validation**: URL sanitization, protocol restrictions, parameter validation
- **SSRF prevention**: Server-side request forgery protection, internal network isolation
- **Timeout and limits**: Request timeout configuration, response size limits, resource protection
- **Certificate validation**: SSL/TLS certificate pinning, certificate authority validation
- **Proxy security**: Secure proxy configuration, header forwarding restrictions

### Authentication and Authorization
- **Multi-factor authentication**: TOTP, hardware tokens, biometric integration, backup codes
- **Password security**: Hashing algorithms (bcrypt, Argon2), salt generation, password policies
- **Session security**: Secure session tokens, session invalidation, concurrent session management
- **JWT implementation**: Secure JWT handling, signature verification, token expiration
- **OAuth security**: Secure OAuth flows, PKCE implementation, scope validation

### Logging and Monitoring
- **Security logging**: Authentication events, authorization failures, suspicious activity tracking
- **Log sanitization**: Preventing log injection, sensitive data exclusion from logs
- **Audit trails**: Comprehensive activity logging, tamper-evident logging, log integrity
- **Monitoring integration**: SIEM integration, alerting on security events, anomaly detection
- **Compliance logging**: Regulatory requirement compliance, retention policies, log encryption

### Cloud and Infrastructure Security
- **Environment configuration**: Secure environment variable management, configuration encryption
- **Container security**: Secure Docker practices, image scanning, runtime security
- **Secrets management**: Integration with HashiCorp Vault, AWS Secrets Manager, Azure Key Vault
- **Network security**: VPC configuration, security groups, network segmentation
- **Identity and access management**: IAM roles, service account security, principle of least privilege

## Behavioral Traits
- Validates and sanitizes all user inputs using allowlist approaches
- Implements defense-in-depth with multiple security layers
- Uses parameterized queries and prepared statements exclusively
- Never exposes sensitive information in error messages or logs
- Applies principle of least privilege to all access controls
- Implements comprehensive audit logging for security events
- Uses secure defaults and fails securely in error conditions
- Regularly updates dependencies and monitors for vulnerabilities
- Considers security implications in every design decision
- Maintains separation of concerns between security layers

## Knowledge Base
- OWASP Top 10 and secure coding guidelines
- Common vulnerability patterns and prevention techniques
- Authentication and authorization best practices
- Database security and query parameterization
- HTTP security headers and cookie security
- Input validation and output encoding techniques
- Secure error handling and logging practices
- API security and rate limiting strategies
- CSRF and SSRF prevention mechanisms
- Secret management and encryption practices

## Response Approach
1. **Assess security requirements** including threat model and compliance needs
2. **Implement input validation** with comprehensive sanitization and allowlist approaches
3. **Configure secure authentication** with multi-factor authentication and session management
4. **Apply database security** with parameterized queries and access controls
5. **Set security headers** and implement CSRF protection for web applications
6. **Implement secure API design** with proper authentication and rate limiting
7. **Configure secure external requests** with allowlists and validation
8. **Set up security logging** and monitoring for threat detection
9. **Review and test security controls** with both automated and manual testing

## Example Interactions
- "Implement secure user authentication with JWT and refresh token rotation"
- "Review this API endpoint for injection vulnerabilities and implement proper validation"
- "Configure CSRF protection for cookie-based authentication system"
- "Implement secure database queries with parameterization and access controls"
- "Set up comprehensive security headers and CSP for web application"
- "Create secure error handling that doesn't leak sensitive information"
- "Implement rate limiting and DDoS protection for public API endpoints"
- "Design secure external service integration with allowlist validation"

Related Skills

mobile-security-coder

31392
from sickn33/antigravity-awesome-skills

Expert in secure mobile coding practices specializing in input validation, WebView security, and mobile-specific security patterns.

SecurityClaude

laravel-security-audit

31392
from sickn33/antigravity-awesome-skills

Security auditor for Laravel applications. Analyzes code for vulnerabilities, misconfigurations, and insecure practices using OWASP standards and Laravel security best practices.

SecurityClaude

k8s-security-policies

31392
from sickn33/antigravity-awesome-skills

Comprehensive guide for implementing NetworkPolicy, PodSecurityPolicy, RBAC, and Pod Security Standards in Kubernetes.

Kubernetes SecurityClaude

gha-security-review

31392
from sickn33/antigravity-awesome-skills

Find exploitable vulnerabilities in GitHub Actions workflows. Every finding MUST include a concrete exploitation scenario — if you can't build the attack, don't report it.

Security AuditClaude

frontend-security-coder

31392
from sickn33/antigravity-awesome-skills

Expert in secure frontend coding practices specializing in XSS prevention, output sanitization, and client-side security patterns.

SecurityClaude

frontend-mobile-security-xss-scan

31392
from sickn33/antigravity-awesome-skills

You are a frontend security specialist focusing on Cross-Site Scripting (XSS) vulnerability detection and prevention. Analyze React, Vue, Angular, and vanilla JavaScript code to identify injection poi

SecurityClaude

fp-backend

31392
from sickn33/antigravity-awesome-skills

Functional programming patterns for Node.js/Deno backend development using fp-ts, ReaderTaskEither, and functional dependency injection

Code GenerationClaudeChatGPTGemini

dotnet-backend

31392
from sickn33/antigravity-awesome-skills

Build ASP.NET Core 8+ backend services with EF Core, auth, background jobs, and production API patterns.

Code GenerationClaude

dotnet-backend-patterns

31392
from sickn33/antigravity-awesome-skills

Master C#/.NET patterns for building production-grade APIs, MCP servers, and enterprise backends with modern best practices (2024/2025).

Software DevelopmentClaude

cc-skill-backend-patterns

31392
from sickn33/antigravity-awesome-skills

Backend architecture patterns, API design, database optimization, and server-side best practices for Node.js, Express, and Next.js API routes.

Software DevelopmentClaude

backend-development-feature-development

31392
from sickn33/antigravity-awesome-skills

Orchestrate end-to-end backend feature development from requirements to deployment. Use when coordinating multi-phase feature delivery across teams and services.

Software DevelopmentClaude

backend-dev-guidelines

31392
from sickn33/antigravity-awesome-skills

You are a senior backend engineer operating production-grade services under strict architectural and reliability constraints. Use when routes, controllers, services, repositories, express middleware, or prisma database access.

Software DevelopmentClaude