我正在用ASP.NET核心(2.2)开发一个简单的API。API使用POST获取一些值,进行一些计算,并返回一个双数组。
API应该只适用于2-3台服务器。什么是最好的认证方法?我在想,我只是给每个服务器一个密钥,他们必须发送每个请求,只需在控制器中询问密钥是否有效(或者检查ip地址)。
这是正确的方法还是我应该实现一个过滤器(看起来更耗时)?
[HttpPost]
public outputModel Post([FromBody] inputmodel input)
{
double[] dbldummy = new double[115];
if (!input.apikey=="12345")
{
return null;
}
//do some calculations and fill otp
return otp;
}发布于 2019-08-08 12:07:16
您可以创建身份验证中间件类,它将执行需要在API调用中传递的基本身份验证。
在API项目中添加以下类
public class AuthenticationMiddleware
{
private readonly RequestDelegate _next;
//IConfiguration _ic;
public AuthenticationMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
//string dbConn2 = configuration.GetValue<string>("MySettings:DbConnection");
string AuthKey = ConfigurationManager.AppSetting["AuthKey"];
string AuthPass = ConfigurationManager.AppSetting["AuthPass"];
string authHeader = context.Request.Headers["Authorization"];
if (authHeader != null && authHeader.StartsWith("Basic"))
{
try
{
//Extract credentials
string encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
Encoding encoding = Encoding.GetEncoding("iso-8859-1");
string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));
int seperatorIndex = usernamePassword.IndexOf(':');
var username = usernamePassword.Substring(0, seperatorIndex);
var password = usernamePassword.Substring(seperatorIndex + 1);
//string username1 = Encryption.Encrypt("test", username);
//string password1 = Encryption.Encrypt("test", password);
if (username == AuthKey && password == AuthPass)
{
await _next.Invoke(context);
}
else
{
context.Response.StatusCode = 401; //Unauthorized
return;
}
}
catch (Exception ex)
{
context.Response.StatusCode = 401; //Unauthorized
return;
}
}
else
{
context.Response.Headers["WWW-Authenticate"] = "Basic realm=\"ABCProject\"";
// no authorization header
context.Response.StatusCode = 401; //Unauthorized
return;
}
}
}在startup.cs中添加以下代码,这些代码将将上述类与应用程序绑定
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCors("AllowAllHeaders");
app.UseMiddleware<AuthenticationMiddleware>();
app.UseHttpsRedirection();
app.UseMvc();
}所有请求都将被重定向到该类,并将检查请求是否包含特定的授权头,然后它将通过401个未经授权的状态代码提供OP,如果它不包含标头
https://stackoverflow.com/questions/57410629
复制相似问题