
使用NestJS和Prisma構建REST API:身份驗證
概述:強大的 API 安全性的重要性怎么強調都不為過。在這個網絡威脅猖獗的時代,保護我們的 API 端點不僅是必需品,也是我們的責任。讓我們剖析這些關鍵的安全措施,并巧妙地實施它們。讓我們討論以下 12 個主題,以使我們的 API 更安全:使用 HTTPS 使用 OAuth2 使用速率限制 使用 API 版本控制 輸入驗證 使用分級 API 密鑰 授權 白名單 OWASP API 安全風險 使用 API 網關 錯誤處理 輸入驗證 使用 HTTPS問題陳述:您的 API 通過 Internet 傳輸敏感數據,并且當前使用不安全的 HTTP。
強大的 API 安全性的重要性怎么強調都不為過。在這個網絡威脅猖獗的時代,保護我們的 API 端點不僅是必需品,也是我們的責任。讓我們剖析這些關鍵的安全措施,并巧妙地實施它們。
讓我們討論以下 12 個主題,以使我們的 API 更安全:
問題陳述:您的 API 通過 Internet 傳輸敏感數據,并且當前使用不安全的 HTTP。如何保護傳輸中的數據?
解決方案:實現HTTPS對客戶端和服務器之間的通信進行加密。
C# 示例:
public class SecureApiController : ApiController
{
// Use attribute to enforce HTTPS
[RequireHttps]
public HttpResponseMessage GetSensitiveData()
{
// Fetch sensitive data logic
var sensitiveData = new { /* ... */ };
return Request.CreateResponse(HttpStatusCode.OK, sensitiveData);
}
}
// Custom attribute to enforce HTTPS
public class RequireHttpsAttribute : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
{
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
{
ReasonPhrase = "HTTPS Required"
};
}
else
{
base.OnAuthorization(actionContext);
}
}
}
始終使用 HTTPS 來保護客戶端和服務器之間的通信。在 ASP.NET Core 中,可以在以下位置強制執行 HTTPS:Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpsRedirection(options =>
{
options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect;
options.HttpsPort = 443;
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseHttpsRedirection();
}
問題陳述:您的 API 需要保護提供個人用戶數據的資源服務器。您需要確保只有經過身份驗證和授權的客戶端才能訪問此數據。
解決方案:實現 OAuth2(一種授權協議),以向客戶端提供安全的受限訪問令牌。
C# 示例:
// OAuth2 configuration in Startup.cs
public void ConfigureAuth(IAppBuilder app)
{
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/Authorize"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
// In production mode set AllowInsecureHttp = false
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
}
實現 OAuth 2.0 授權框架。它支持安全的委托訪問,允許客戶端獲取有限的訪問令牌來驗證 API 請求。在 ASP.NET Core 中,可以使用 Microsoft Identity 平臺:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(Configuration, "AzureAd");
services.AddAuthorization(options =>
{
options.AddPolicy("RequireAdminRole", policy =>
{
policy.RequireRole("Admin");
});
});
問題陳述:您的 API 流量過大,導致性能下降。您需要實現速率限制來控制流量。
解決方案:使用中間件根據 IP、用戶或操作組強制實施速率限制規則。
C# 示例:
// Middleware for rate limiting
public class RateLimitingMiddleware : OwinMiddleware
{
public RateLimitingMiddleware(OwinMiddleware next) : base(next) { }
public override async Task Invoke(IOwinContext context)
{
if (RateLimitReached(context))
{
context.Response.StatusCode = (int)HttpStatusCode.TooManyRequests;
return;
}
await Next.Invoke(context);
}
private bool RateLimitReached(IOwinContext context)
{
// Implement your rate limiting logic here based on the context
// For instance, check the IP address and limit the number of requests per minute
return false;
}
}
實施速率限制以限制客戶端在給定時間窗口內可以發出的請求數。您可以根據客戶端 IP、用戶 ID、API 路由等各種因素定義速率限制。下面是使用 AspNetCoreRateLimit 的示例:
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.AddMemoryCache();
services.Configure\<ClientRateLimitOptions>(options =>
{
options.GeneralRules = new List\<RateLimitRule>
{
new RateLimitRule
{
Endpoint = "\*",
Period = "1m",
Limit = 30,
}
};
});
services.AddSingleton<IClientPolicyStore, MemoryCacheClientPolicyStore>();
services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
}
public void Configure(IApplicationBuilder app)
{
app.UseClientRateLimiting();
}
問題陳述:您的 API 需要在不破壞現有客戶端的情況下進行發展。如何在保持向后兼容性的同時引入新功能?
解決方案:在 API 路由中實現版本控制,以允許客戶端指定它們設計用于使用的版本。
C# 示例:
// Web API Route configuration
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "VersionedApi",
routeTemplate: "api/v{version}/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
public class UsersController : ApiController
{
[HttpGet]
public string GetV1(int id)
{
// Version 1 specific processing
return "Data from version 1";
}
[HttpGet, Route("api/v2/users/{id}")]
public string GetV2(int id)
{
// Version 2 specific processing
return "Data from version 2";
}
}
實施 API 版本控制以保持向后兼容性。在 API 路由中包含版本指示符(如“v1”),也可以在請求/響應標頭中包含版本指示符。ASP.NET Core 通過軟件包支持此功能:Microsoft.AspNetCore.Mvc.Versioning
services.AddApiVersioning(options =>
{
options.DefaultApiVersion = new ApiVersion(1, 0);
options.AssumeDefaultVersionWhenUnspecified = true;
options.ReportApiVersions = true;
options.ApiVersionReader = new UrlSegmentApiVersionReader();
});
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class UsersController : ControllerBase
{
// Controller implementation
}
問題:在未經適當驗證的情況下接受來自客戶端的不受信任的輸入可能會引入 SQL 注入或跨站點腳本 (XSS) 等安全漏洞。
解決方案:始終在服務器端驗證和清理輸入。使用數據注釋和屬性進行基本驗證:[ApiController]
public class LoginModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[StringLength(100, MinimumLength = 6)]
public string Password { get; set; }
}
[HttpPost("login")]
public IActionResult Login([FromBody] LoginModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// Authenticate user
}
在 API 網關級別實現輸入驗證,以確保僅處理有效請求。
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(
HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
}
// Usage in a Controller
public class MyModel
{
[Required]
public string Property1 { get; set; }
// Other properties and validation attributes
}
public class MyApiController : ApiController
{
[ValidateModel]
public IHttpActionResult Post(MyModel model)
{
// Proceed knowing the model is valid
ProcessData(model);
return Ok();
}
private void ProcessData(MyModel model)
{
// Processing logic
}
}
問題:對所有客戶端使用單個 API 密鑰無法提供精細控制,也無法根據需要撤銷對特定客戶端的訪問權限。
解決方案:實現具有不同訪問權限的分級 API 密鑰系統。每個客戶端都獲得與特定角色或范圍關聯的唯一密鑰。
public class ApiKey
{
public int Id { get; set; }
public string Key { get; set; }
public string ClientName { get; set; }
public List<string> Scopes { get; set; }
}
public class AuthorizationMiddleware
{
private readonly RequestDelegate _next;
public AuthorizationMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context, IApiKeyRepository apiKeyRepository)
{
string apiKey = context.Request.Headers["X-API-KEY"];
if (apiKey == null)
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("API key is missing.");
return;
}
ApiKey key = await apiKeyRepository.GetApiKey(apiKey);
if (key == null)
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Invalid API key.");
return;
}
if (!key.Scopes.Contains(context.Request.Path.ToString()))
{
context.Response.StatusCode = 403;
await context.Response.WriteAsync("Not authorized to access this resource.");
return;
}
await _next(context);
}
}
實現具有不同訪問權限的分級 API 密鑰。
public class ApiKeyHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// Validate API key
if (!ValidateApiKey(request.Headers, out var apiKey))
{
return request.CreateResponse(HttpStatusCode.Forbidden, "Invalid API Key");
}
// Check access level of API key and set user's role
SetUserRoleBasedOnApiKey(apiKey);
// Continue down the pipeline
return await base.SendAsync(request, cancellationToken);
}
private bool ValidateApiKey(HttpRequestHeaders headers, out string apiKey)
{
// Logic to validate API key
apiKey = /* ... */;
return true;
}
private void SetUserRoleBasedOnApiKey(string apiKey)
{
// Logic to set user role based on API key level
}
}
問題:如果沒有適當的授權檢查,經過身份驗證的用戶可能會訪問他們不應該被允許訪問的資源。
解決方案:在允許請求繼續之前,實現基于角色的訪問控制 (RBAC) 并檢查每個 API 端點上的用戶權限。
[Authorize(Roles = "Admin")]
[HttpDelete("users/{id}")]
public async Task<IActionResult> DeleteUser(int id)
{
// Delete user logic
return NoContent();
}
在更復雜的場景中,您可能需要實現基于屬性的訪問控制 (ABAC) 或基于策略的授權。
在 API 中實施授權檢查,以區分用戶的不同訪問權限級別。
[Authorize(Roles = "Admin, Viewer")]
public class DataController : ApiController
{
public IHttpActionResult GetData()
{
// Only users with role "Admin" or "Viewer" can access data
var data = GetDataFromService();
return Ok(data);
}
[Authorize(Roles = "Admin")]
public IHttpActionResult UpdateData(MyDataModel model)
{
// Only users with role "Admin" can update data
UpdateDataService(model);
return Ok();
}
// Separate methods to get and update data
private object GetDataFromService() { /*...*/ }
private void UpdateDataService(MyDataModel model) { /*...*/ }
}
問題:某些 API 端點可能設計為僅接受一組有限的預定義參數值。允許任意輸入可使攻擊者繞過驗證或注入惡意數據。
解決方案:使用白名單(或白名單)顯式定義敏感參數的允許值。
[HttpGet("articles")]
public IActionResult GetArticles([FromQuery] string category)
{
string[] allowedCategories = { "science", "technology", "business" };
if (!allowedCategories.Contains(category))
{
return BadRequest("Invalid category.");
}
// Fetch and return articles in the specified category
}
public class IPAllowlistHandler : DelegatingHandler
{
private readonly string[] _trustedIPs;
public IPAllowlistHandler(string[] trustedIPs)
{
_trustedIPs = trustedIPs ?? throw new ArgumentNullException(nameof(trustedIPs));
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var context = ((HttpContextBase)request.Properties["MS_HttpContext"\]);
var requestIP = context.Request.UserHostAddress;
if (!_trustedIPs.Contains(requestIP))
{
return Task.FromResult(request.CreateResponse(HttpStatusCode.Forbidden, "Access denied from this IP address"));
}
return base.SendAsync(request, cancellationToken);
}
}
問題陳述:您的 API 受到各種安全威脅和漏洞的影響。您如何確保它們免受 OWASP 識別的主要安全風險的影響?
解決方案:根據 OWASP API 安全前 10 名列表定期審核和更新您的 API,該列表詳細說明了 Web 應用程序面臨的最關鍵安全風險。
C# 示例:
// Example of checking for broken user authentication, which is a common OWASP risk
public class AuthenticationMiddleware : OwinMiddleware
{
public AuthenticationMiddleware(OwinMiddleware next) : base(next) {}
public override async Task Invoke(IOwinContext context)
{
if (!UserIsAuthenticated(context))
{
context.Response.StatusCode = 401; // Unauthorized
await context.Response.WriteAsync("User authentication failed.");
return;
}
await Next.Invoke(context);
}
private bool UserIsAuthenticated(IOwinContext context)
{
// Implement your authentication logic here
// Make sure it's in line with OWASP recommendations
return true; // Placeholder for actual authentication check
}
}
問題:隨著微服務和 API 端點數量的增加,管理身份驗證、速率限制和監控等方面可能會變得復雜且容易出錯。
解決方案:使用 API Gateway 作為所有客戶端請求的單一入口點。它可以處理請求路由、組合和協議轉換等常見任務。常用選項包括 Azure API 管理、Amazon API Gateway 或使用 Ocelot 構建自己的 API。
// Configure API Gateway routes
var routes = new List<RouteConfiguration>
{
new RouteConfiguration
{
RouteId = "users-route",
UpstreamPathTemplate = "/api/users/{everything}",
DownstreamPathTemplate = "/api/users/{everything}",
DownstreamScheme = "https",
DownstreamHostAndPorts = new List<DownstreamHostAndPort>
{
new DownstreamHostAndPort
{
Host = "users-service",
Port = 443
}
}
},
// Additional route configurations
};
var config = new OcelotPipelineConfiguration
{
Routes = routes
};
// Configure authentication middleware
services.AddAuthentication()
.AddJwtBearer("users-service", options =>
{
// JWT bearer configuration for users service
})
.AddJwtBearer("products-service", options =>
{
// JWT bearer configuration for products service
});
await ocelotBuilder.AddOcelot(config)
.AddDelegatingHandler\<AuthenticationDelegatingHandler>()
.Build()
.StartAsync();
將 API Gateway 實現為微服務的單一入口點。它可以處理跨領域問題,如身份驗證、SSL 終止和速率限制。
public class ApiGatewayHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// Pre-processing: authentication, logging, etc.
AuthenticateRequest(request);
// Route to the appropriate service
var response = RouteToService(request);
// Post-processing: modify response, add headers, etc.
return await ProcessResponse(response);
}
private void AuthenticateRequest(HttpRequestMessage request)
{
// Authentication logic
}
private Task<HttpResponseMessage> RouteToService(HttpRequestMessage request)
{
// Logic to route to specific services
// This is a placeholder for actual routing logic
return Task.FromResult(new HttpResponseMessage());
}
private async Task<HttpResponseMessage> ProcessResponse(HttpResponseMessage response)
{
// Response processing logic
return response;
}
}
問題:向客戶端公開詳細的錯誤消息可能會泄露有關 API 內部的敏感信息,從而可能幫助攻擊者。
解決方案:實施全局錯誤處理策略,以在 API 中一致地捕獲和處理異常。將一般的、不敏感的錯誤消息返回給客戶端,同時在服務器端記錄詳細的錯誤信息以進行調試。
public class ErrorDetails
{
public int StatusCode { get; set; }
public string Message { get; set; }
}
public class GlobalExceptionFilter : IExceptionFilter
{
private readonly ILogger<GlobalExceptionFilter> _logger;
public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
{
_logger = logger;
}
public void OnException(ExceptionContext context)
{
int statusCode = StatusCodes.Status500InternalServerError;
string message = "An unexpected error occurred.";
if (context.Exception is ArgumentException)
{
statusCode = StatusCodes.Status400BadRequest;
message = "Invalid request data.";
}
else if (context.Exception is UnauthorizedAccessException)
{
statusCode = StatusCodes.Status401Unauthorized;
message = "Authentication required.";
}
// Handle other specific exception types
_logger.LogError(context.Exception, "Unhandled exception occurred.");
context.Result = new ObjectResult(new ErrorDetails
{
StatusCode = statusCode,
Message = message
})
{
StatusCode = statusCode
};
context.ExceptionHandled = true;
}
}
// Register the global exception filter
services.AddControllers(options =>
{
options.Filters.Add<GlobalExceptionFilter>();
});
創建一個自定義錯誤處理程序,該處理程序在不公開敏感詳細信息的情況下返回描述性和有用的錯誤消息。
public class GlobalExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
// Log the exception details for internal use
LogException(context.Exception);
// Provide a friendly error message to the client
var result = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent("An unexpected error occurred. Please try again later."),
ReasonPhrase = "Critical Exception"
};
context.Result = new ErrorMessageResult(context.Request, result);
}
private void LogException(Exception exception)
{
// Implement logging logic
}
}
public class ErrorMessageResult : IHttpActionResult
{
private readonly HttpRequestMessage _request;
private readonly HttpResponseMessage _httpResponseMessage;
public ErrorMessageResult(HttpRequestMessage request, HttpResponseMessage httpResponseMessage)
{
_request = request;
_httpResponseMessage = httpResponseMessage;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
return Task.FromResult(_httpResponseMessage);
}
}
// Register in WebApiConfig
config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());
問題:在未經適當驗證的情況下接受來自客戶端的不受信任的輸入可能會引入 SQL 注入或跨站點腳本 (XSS) 等安全漏洞。
解決方案:始終在服務器端驗證和清理輸入。使用數據注釋和屬性進行基本驗證:[ApiController]
public class CreateUserModel
{
[Required]
[StringLength(50)]
public string Username { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[StringLength(100, MinimumLength = 6)]
public string Password { get; set; }
}
[HttpPost]
public IActionResult CreateUser([FromBody] CreateUserModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// Create user logic
return CreatedAtAction(nameof(GetUser), new { id = user.Id }, user);
}
public class CreateUserValidator : AbstractValidator<CreateUserModel>
{
public CreateUserValidator()
{
RuleFor(x => x.Username)
.NotEmpty()
.MaximumLength(50);
RuleFor(x => x.Email)
.NotEmpty()
.EmailAddress();
RuleFor(x => x.Password)
.NotEmpty()
.Length(6, 100);
}
}
[HttpPost]
public IActionResult CreateUser([FromBody] CreateUserModel model)
{
var validator = new CreateUserValidator();
var validationResult = validator.Validate(model);
if (!validationResult.IsValid)
{
return BadRequest(validationResult.Errors);
}
// Create user logic
return CreatedAtAction(nameof(GetUser), new { id = user.Id }, user);
}
請記住,輸入驗證不是靈丹妙藥。它應與其他安全措施(如參數化查詢、輸出編碼和內容安全策略)結合使用,以構建針對注入攻擊的全面防御。
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(
HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
}
// Usage in a Controller
public class MyModel
{
[Required]
public string Property1 { get; set; }
// Other properties and validation attributes
}
public class MyApiController : ApiController
{
[ValidateModel]
public IHttpActionResult Post(MyModel model)
{
// Proceed knowing the model is valid
ProcessData(model);
return Ok();
}
private void ProcessData(MyModel model)
{
// Processing logic
}
}
問題:不安全的編碼做法可能會引入攻擊者可以利用的漏洞,從而危及 API 的安全性。
解決方案:遵循安全編碼準則和最佳做法,以最大程度地降低漏洞風險:
問題:如果您不主動查找安全漏洞,它們可能無法檢測到,從而使您的 API 暴露在潛在攻擊之下。
解決方案:將安全測試納入開發生命周期:
通過將安全測試作為開發過程的常規部分,您可以主動識別和解決漏洞,以免被惡意行為者利用。
問題:如果沒有適當的日志記錄和監視,您可能會錯過關鍵的安全事件或無法檢測到正在進行的攻擊。
解決方案:對 API 實施全面的日志記錄和監視:
通過實施強大的日志記錄和監控,您可以了解 API 的安全狀況,及早檢測威脅,并快速響應以減輕任何事件的影響。
請記住,API 安全是一項多方面的工作,需要整體方法。通過結合安全編碼實踐、定期測試以及全面的日志記錄和監控,您可以構建能夠抵御各種威脅的 API。
在繼續開發和改進 API 的過程中,請始終將安全性放在首位。隨時了解最新的安全最佳實踐、工具和技術。與安全社區互動,參加會議和研討會,并不斷對自己和您的團隊進行有關 API 安全的教育。
通過在整個 API 開發生命周期中優先考慮安全性,您可以創建不僅功能強大、性能高,而且安全可靠且值得信賴的 API。???
本文章轉載微信公眾號@架構師老盧