Home >Backend Development >C++ >How to Secure Your API Against Unauthorized Requests

How to Secure Your API Against Unauthorized Requests

DDD
DDDOriginal
2025-01-23 00:15:09868browse

How to Secure Your API Against Unauthorized Requests

In modern applications, APIs play a vital role, connecting different systems. However, APIs are also common targets for unauthorized access and abuse. API security requires multiple layers of protection, combining CORS validation, strong authentication mechanisms, and reliable monitoring. This article will describe several strategies for securing your API to ensure that only trusted clients can access it.


1. Correctly configure CORS

Cross-Origin Resource Sharing (CORS) is an important security mechanism that determines which origins can interact with your API. Correctly configuring CORS is critical to prevent unauthorized access.

ASP.NET Core example:

<code class="language-csharp">builder.Services.AddCors(options =>
{
    options.AddPolicy("RestrictOrigins", policy =>
    {
        policy.WithOrigins("https://mywebsite.com", "https://trustedpartner.com") // 允许的来源
              .AllowAnyHeader()
              .AllowAnyMethod();
    });
});

// 应用 CORS 策略
app.UseCors("RestrictOrigins");</code>

Key Rules:

  • Avoid AllowAnyOrigin: Allowing all origins makes your API vulnerable.
  • Don’t use SetIsOriginAllowed(_ => true): this will completely bypass origin verification.
  • Limit methods and headers: Limit AllowAnyMethod and AllowAnyHeader to strictly necessary scope.

2. Implement authentication and authorization

Authentication ensures that only authorized users or systems can access your endpoints. One common method is to use JSON Web Tokens (JWT).

JWT implementation steps:

  1. On the client side, send the JWT in the request header:
<code>   Authorization: Bearer <your-jwt-token></code>
  1. On the server side, verify the token:
<code class="language-csharp">   app.UseAuthentication();
   app.UseAuthorization();</code>

ASP.NET Core sample configuration:

<code class="language-csharp">builder.Services.AddAuthentication("Bearer")
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = "https://mywebsite.com",
            ValidAudience = "https://mywebsite.com",
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("secret-key"))
        };
    });</code>

3. Explicitly verify the Origin header

Even if CORS is configured, you can add an extra layer of security by manually validating the Origin header in server-side middleware.

Example:

<code class="language-csharp">app.Use(async (context, next) =>
{
    var origin = context.Request.Headers["Origin"].ToString();
    var allowedOrigins = new[] { "https://mywebsite.com", "https://trustedpartner.com" };

    if (!string.IsNullOrEmpty(origin) && !allowedOrigins.Contains(origin))
    {
        context.Response.StatusCode = StatusCodes.Status403Forbidden;
        await context.Response.WriteAsync("Origin not allowed.");
        return;
    }

    await next();
});</code>

4. Block suspicious IPs

Filter and block requests from known malicious IP addresses to reduce attack vectors.

Example middleware:

<code class="language-csharp">app.Use(async (context, next) =>
{
    var clientIp = context.Connection.RemoteIpAddress;
    var blockedIps = new[] { "192.168.1.100", "10.0.0.50" };

    if (blockedIps.Contains(clientIp.ToString()))
    {
        context.Response.StatusCode = StatusCodes.Status403Forbidden;
        await context.Response.WriteAsync("Blocked IP.");
        return;
    }

    await next();
});</code>

5. Implement rate limiting

Protect your API from abuse and brute force attacks by limiting the number of requests a client can make.

ASP.NET Core example:

Install the package:

<code class="language-bash">dotnet add package AspNetCoreRateLimit</code>

Configure rate limit:

<code class="language-csharp">builder.Services.AddMemoryCache();
builder.Services.Configure<IpRateLimitOptions>(options =>
{
    options.GeneralRules = new List<RateLimitRule>
    {
        new RateLimitRule
        {
            Endpoint = "*",
            Limit = 100, // 请求限制
            Period = "1m" // 每分钟
        }
    };
});

builder.Services.AddInMemoryRateLimiting();
app.UseIpRateLimiting();</code>

6. Use HTTPS for all connections

Ensure secure communication between clients and your API by forcing the use of HTTPS.

Configure HTTPS in ASP.NET Core:

<code class="language-csharp">webBuilder.UseKestrel()
          .UseHttps();</code>

Redirect HTTP traffic to HTTPS:

<code class="language-csharp">app.UseHttpsRedirection();</code>

7. Monitoring and logging requests

Implement logging to detect unusual patterns, such as multiple requests from unknown sources.

Example:

<code class="language-csharp">app.Use(async (context, next) =>
{
    var origin = context.Request.Headers["Origin"].ToString();
    Console.WriteLine($"Request from origin: {origin}");
    await next();
});</code>

Use tools like Application Insights, Serilog or Elastic Stack for comprehensive monitoring.


8. Avoid detailed error responses

Do not expose sensitive information in error messages as it may help attackers.

Example:

<code class="language-csharp">builder.Services.AddCors(options =>
{
    options.AddPolicy("RestrictOrigins", policy =>
    {
        policy.WithOrigins("https://mywebsite.com", "https://trustedpartner.com") // 允许的来源
              .AllowAnyHeader()
              .AllowAnyMethod();
    });
});

// 应用 CORS 策略
app.UseCors("RestrictOrigins");</code>

Conclusion

Securing your API from unauthorized requests requires a multi-layered approach:

  1. Properly configure CORS.
  2. Explicitly verify sources and headers.
  3. Implements Authentication and Rate Limiting.
  4. Use HTTPS and monitor traffic.

By following these best practices, you can significantly reduce the risk of unauthorized access and ensure that only trusted clients can interact with your API.

The above is the detailed content of How to Secure Your API Against Unauthorized Requests. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn