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.
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.
<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>
Authentication ensures that only authorized users or systems can access your endpoints. One common method is to use JSON Web Tokens (JWT).
<code> Authorization: Bearer <your-jwt-token></code>
<code class="language-csharp"> app.UseAuthentication(); app.UseAuthorization();</code>
<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>
Even if CORS is configured, you can add an extra layer of security by manually validating the Origin header in server-side middleware.
<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>
Filter and block requests from known malicious IP addresses to reduce attack vectors.
<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>
Protect your API from abuse and brute force attacks by limiting the number of requests a client can make.
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>
Ensure secure communication between clients and your API by forcing the use of HTTPS.
<code class="language-csharp">webBuilder.UseKestrel() .UseHttps();</code>
Redirect HTTP traffic to HTTPS:
<code class="language-csharp">app.UseHttpsRedirection();</code>
Implement logging to detect unusual patterns, such as multiple requests from unknown sources.
<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.
Do not expose sensitive information in error messages as it may help attackers.
<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>
Securing your API from unauthorized requests requires a multi-layered approach:
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!