[Route("api/[controller]")]
public class MyController : ControllerBase
{
[Authorize] // 需要身份驗(yàn)證才能訪問(wèn)此端點(diǎn)
[HttpGet]
public IActionResult Get()
{
// 邏輯在這里
return Ok("經(jīng)過(guò)身份驗(yàn)證的用戶(hù)可以訪問(wèn)此資源.");
}
}

基于令牌的身份驗(yàn)證

基于令牌的身份驗(yàn)證是一種被廣泛使用的方法,通過(guò)向已認(rèn)證的用戶(hù)頒發(fā)唯一令牌,隨后?API?請(qǐng)求憑此令牌進(jìn)行驗(yàn)證。最常用的令牌生成機(jī)制是?JWT?令牌(JSON?Web?Token)。以下是使用?C#?創(chuàng)建?JWT?令牌以對(duì)用戶(hù)進(jìn)行身份驗(yàn)證的示例。

public IActionResult Authenticate()
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes("your_secret_key");
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, "Shubhadeep Chattopadhyay"),
// 根據(jù)需要添加更多
}),
Expires = DateTime.UtcNow.AddDays(1),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
return Ok(new { Token = tokenString });
}

API?密鑰

API?密鑰是授予用戶(hù)或應(yīng)用程序以訪問(wèn)特定?API?的唯一標(biāo)識(shí)符。它們充當(dāng)一種簡(jiǎn)單的身份驗(yàn)證形式,需要在?API?調(diào)用時(shí)作為?HTTP?標(biāo)頭信息傳遞。以下是使用?C#?驗(yàn)證密鑰的示例。在實(shí)際實(shí)現(xiàn)時(shí),邏輯應(yīng)該是集中的。

[ApiController]
[Route("api/[controller]")]
public class MyController : ControllerBase
{
private const string ApiKey = "your_api_key";

[HttpGet]
public IActionResult Get()
{
var apiKey = Request.Headers["Api-Key"].FirstOrDefault();
if (apiKey != ApiKey)
return Unauthorized();

// 這里的邏輯
return Ok("在Startup.cs中,將以下內(nèi)容添加到Configure方法中.");
}
}

速率限制

速率限制,是對(duì)用戶(hù)或應(yīng)用程序在特定時(shí)間范圍內(nèi)可以向 API 發(fā)出請(qǐng)求數(shù)量的限制。這有助于防止濫用行為,確保資源被公平合理地利用。

下面是使用?ASP.Net?Core?中間件實(shí)現(xiàn)速率限制的示例,每分鐘僅允許?100?個(gè)調(diào)用。

public class RateLimitingMiddleware
{
private readonly RequestDelegate _next;
private readonly int _requestLimit;
private readonly TimeSpan _timeFrame;
private readonly ConcurrentDictionary<string, int> _requestCount = new ConcurrentDictionary<string, int>();

public RateLimitingMiddleware(RequestDelegate next, int requestLimit, TimeSpan timeFrame)
{
_next = next;
_requestLimit = requestLimit;
_timeFrame = timeFrame;
}

public async Task InvokeAsync(HttpContext context)
{
var ipAddress = context.Connection.RemoteIpAddress.ToString();
var currentTime = DateTime.UtcNow;

if (_requestCount.TryGetValue(ipAddress, out var count) && (currentTime - TimeSpan.FromMinutes(1)) < _timeFrame)
{
if (count > _requestLimit)
{
context.Response.StatusCode = (int)HttpStatusCode.TooManyRequests;
return;
}

_requestCount[ipAddress] = ++count;
}
else
{
_requestCount[ipAddress] = 1;
}

await _next(context);
}
}

// In Startup.cs, add the following to the Configure method:
app.UseMiddleware<RateLimitingMiddleware>(requestLimit: 100, timeFrame: TimeSpan.FromMinutes(1));

輸入驗(yàn)證

正確的輸入驗(yàn)證對(duì)于防止注入攻擊和數(shù)據(jù)操縱至關(guān)重要。始終驗(yàn)證和清理傳入數(shù)據(jù),以確保數(shù)據(jù)的完整性和安全性。

以下是使用?ASP.NET?Core?數(shù)據(jù)注釋進(jìn)行輸入驗(yàn)證的示例。如果請(qǐng)求正文無(wú)效,則不會(huì)接受并返回錯(cuò)誤請(qǐng)求。

public class UserController : ControllerBase
{
[HttpPost]
public IActionResult CreateUser([FromBody] User user)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);

// Your logic to create the user
return Ok("User created successfully.");
}
}

public class User
{
[Required]
public string Username { get; set; }

[Required]
[EmailAddress]
public string Email { get; set; }

[Required]
[StringLength(8, MinimumLength = 4)]
public string Password { get; set; }
}

TLS/SSL?加密

傳輸層安全性 (TLS) 或安全套接字層 (SSL) 加密可確??蛻?hù)端和 API 服務(wù)器之間的安全通信。

以下是在?ASP.NET?Core?啟動(dòng)類(lèi)中啟用?HTTPS?的示例。

public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Other service configurations
services.AddHttpsRedirection(options =>
{
options.HttpsPort = 443; // Default HTTPS port
});
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// Other app configurations

app.UseHttpsRedirection();
}
}

跨域資源共享?(CORS)

CORS 防止未經(jīng)授權(quán)的域外訪問(wèn)您的 API。對(duì)于所有開(kāi)發(fā)人員來(lái)說(shuō),這是非常常見(jiàn)的做法,僅允許特定域請(qǐng)求才能被處理。

以下是在?ASP.NET?中配置?CORS?的示例。

public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Other service configurations

services.AddCors(options =>
{
options.AddPolicy("AllowMyDomain", builder =>
{
builder.WithOrigins("https://www.knowndoamin.com")
.AllowAnyMethod()
.AllowAnyHeader();
});
});
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// Other app configurations

app.UseCors("AllowMyDomain");
}
}

記錄和監(jiān)控

全面的日志記錄和監(jiān)控有助于深入了解 API 的使用情況,發(fā)現(xiàn)潛在的安全漏洞和性能問(wèn)題。

以下是使用?ASP.Net?和?Serilog?啟用日志記錄的示例。

// In Startup.cs
public class Startup
{
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// Other app configurations

Log.Logger = new LoggerConfiguration()
.WriteTo.File("log.txt")
.CreateLogger();

app.UseSerilogRequestLogging();

// More middleware and configurations
}
}

結(jié)論

除了上述流程,API?安全最佳實(shí)踐還應(yīng)關(guān)注以下四點(diǎn):

● 定期更新和修補(bǔ)依賴(lài)項(xiàng)和庫(kù)。
● 采用最小權(quán)限原則,僅授予必要的權(quán)限。
● 使用安全密碼散列算法(例如 bcrypt)來(lái)存儲(chǔ)密碼。
● 對(duì)關(guān)鍵操作實(shí)施雙因素身份驗(yàn)證。

在研發(fā)流程之外,開(kāi)發(fā)者也可以采用API集成平臺(tái)更好地關(guān)注API安全。比如,API集成平臺(tái)可以幫助設(shè)置訪問(wèn)控制策略,并提供監(jiān)控和日志記錄功能,實(shí)時(shí)預(yù)警,幫助開(kāi)發(fā)者監(jiān)控API使用情況并及時(shí)發(fā)現(xiàn)異常行為。

盡管確保?API?安全是一項(xiàng)多方面的任務(wù),但保護(hù)敏感數(shù)據(jù)并維護(hù)用戶(hù)和客戶(hù)的信任至關(guān)重要。本文探討了?C#?中的各種?API?安全機(jī)制,包括身份驗(yàn)證、基于令牌的身份驗(yàn)證、API?密鑰、速率限制、輸入驗(yàn)證、TLS/SSL?加密、CORS、日志記錄和監(jiān)控。通過(guò)整合這些最佳實(shí)踐,開(kāi)發(fā)人員可以構(gòu)建強(qiáng)大且安全的?API,從而為更安全的數(shù)字生態(tài)系統(tǒng)做出貢獻(xiàn)。

原文鏈接:Best Practices of API Security

上一篇:

各互聯(lián)網(wǎng)商業(yè)業(yè)態(tài)業(yè)務(wù)風(fēng)險(xiǎn)綜述

下一篇:

如何使用Python?SDK與OpenAI?Assistants?API構(gòu)建助手?
#你可能也喜歡這些API文章!

我們有何不同?

API服務(wù)商零注冊(cè)

多API并行試用

數(shù)據(jù)驅(qū)動(dòng)選型,提升決策效率

查看全部API→
??

熱門(mén)場(chǎng)景實(shí)測(cè),選對(duì)API

#AI文本生成大模型API

對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力

25個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)

#AI深度推理大模型API

對(duì)比大模型API的邏輯推理準(zhǔn)確性、分析深度、可視化建議合理性

10個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)