一种方法是使用 API 密钥,但是您会将 API 密钥放在哪里
在反应方面?
是的,您可以创建 API 密钥中间件并使用它来验证请求。如果请求来自 react 应用程序,您可以在请求标头中添加 API 密钥。像这样的代码:
使用 fetch 方法:
fetch('/api/MoviesAPI', {
method: 'Get', // or 'Post'
headers: {
'Content-Type': 'application/json',
'ApiKey':'Test-value',
},
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.log('Error:', error);
});
使用Ajax方法:
$.ajax({
type: "Get",
url: "/api/MoviesAPI", //remember change the controller to your owns.
contentType: 'application/json',
beforeSend: function (xhr) { xhr.setRequestHeader('ApiKey', 'test-value'); },
success: function (data) {
console.log(data)
},
failure: function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log(response.responseText);
}
});
更多关于reactjs中自定义header发送请求的详细信息,你可以用谷歌或者Bing搜索“reactjs call api with custom headers”,相关文章很多。
另外,关于创建 API 密钥中间件,您可以参考以下步骤:
-
在API应用中创建一个ApiKeyMiddleware.cs类,添加如下代码:
public class ApiKeyMiddleware
{
public ApiKeyMiddleware(RequestDelegate next, IConfiguration configuration)
{
_next = next;
_configuration = configuration;
}
private readonly RequestDelegate _next;
private readonly IConfiguration _configuration;
public async Task Invoke(HttpContext context)
{
if (context.Request.Path.StartsWithSegments(new PathString("/api")))
{
//Let's check if this is an API Call
if (context.Request.Headers.Keys.Contains("ApiKey", StringComparer.InvariantCultureIgnoreCase))
{
// validate the supplied API key
// Validate it
var headerKey = context.Request.Headers["ApiKey"].FirstOrDefault();
await ValidateApiKey(context, _next, headerKey);
}
else
{
await _next.Invoke(context);
}
}
else
{
await _next.Invoke(context);
}
}
private async Task ValidateApiKey(HttpContext context, RequestDelegate next, string key)
{
// validate it here
var valid = false;
var Apikey = _configuration["ApiKey"];
if (key != null && key==Apikey)
{
valid = true;
}
if (!valid)
{
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
await context.Response.WriteAsync("Invalid API Key");
}
else
{
var identity = new GenericIdentity("API");
var principal = new GenericPrincipal(identity, new[] { "Admin", "ApiUser" });
context.User = principal;
await next.Invoke(context);
}
}
}
-
在 Startup.cs 文件的 Configure 方法中注册此中间件。
app.UseMiddleware<ApiKeyMiddleware>(); //add APIkeyMiddleware
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication(); //Call the UseAuthentication
app.UseAuthorization();
-
在API控制器或动作方法中,添加Authorize属性。
[HttpGet]
[Authorize]
public async Task<ActionResult> GetMovie()
{
return Ok(await _context.Movie.ToListAsync());
}
那么,如果请求头中不包含ApiKey或者key值无效,则不会返回资源。
编辑:
关于 API 密钥值,您可以将它们存储在 appsettings.json 文件或内存中的 .NET 对象中。使用时可以从配置中获取。
例如:存放在appsettings.json文件中:
{
...
"Apikey": "my Test API key"
}
然后,使用以下代码获取键值
public ApiKeyMiddleware(RequestDelegate next, IConfiguration configuration)
{
_next = next;
_configuration = configuration;
}
private readonly RequestDelegate _next;
private readonly IConfiguration _configuration;
private async Task ValidateApiKey(HttpContext context, RequestDelegate next, string key)
{
// validate it here
var valid = false;
//get the key value from configuration.
var Apikey = _configuration["ApiKey"];
...
在反应方面,您可以创建一个服务来获取此键值,然后使用 api 键发送请求。