我一直在查看有关使用身份验证 token 保护 .NET Core WebAPI 的教程,所有内容似乎都需要用户名/密码组合才能获得用于对 API Controller 进行身份验证的临时 token 。
我正在从事的项目正在使用运行我编写的自定义 UWP 应用程序的 Windows IOT 设备,该应用程序需要在后台连接到此 API 以记录数据并下载最新的设备配置。
我曾计划为每台设备提供一个唯一的 token 以进行身份验证,该 token 将在初始设备/应用程序设置期间输入和存储。我使用过的大多数第三方 API 只是给你一个永久 token ,你可以用它来访问他们的 API。我想做类似的事情。
最佳答案
JWT 对我的目的来说似乎矫枉过正且过于复杂,所以我最终按照本教程采用了中间件解决方案: https://www.youtube.com/watch?v=n0llyujNGw8
我最终使用以下代码创建了一个中间件类:
public class TokenValidationMiddleware
{
private readonly RequestDelegate _next;
public TokenValidationMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
bool validToken = false;
//Require HTTPS
if (context.Request.IsHttps)
{
//Skip token authentication for test controller
if (context.Request.Path.StartsWithSegments("/api/values"))
{
validToken = true;
}
//Token header exists in the request
if (context.Request.Headers.ContainsKey("Token"))
{
//Check for a valid device by API token in my DB and set validToken to true if found
if (repository.FindDeviceByAPIKey())
{
validToken = true;
}
}
if (!validToken)
{
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
await context.Response.WriteAsync("Invalid Token");
}
else
{
await _next.Invoke(context);
}
}
else
{
context.Response.StatusCode = (int)HttpStatusCode.HttpVersionNotSupported;
await context.Response.WriteAsync("HTTP not supported");
}
}
}
public static class TokenExtensions
{
public static IApplicationBuilder UseTokenAuth(this IApplicationBuilder builder)
{
return builder.UseMiddleware<TokenValidationMiddleware>();
}
}
然后我刚刚添加了 app.UseTokenAuth();到我的创业类
关于authentication - .NET Core WebAPI 永久 token 认证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48942574/