【问题标题】:.NET Core WebAPI permanent token authentication.NET Core WebAPI 永久令牌身份验证
【发布时间】:2018-08-03 04:45:35
【问题描述】:
我一直在看一个又一个关于使用身份验证令牌保护 .NET Core WebAPI 的教程,一切似乎都需要用户名/密码组合才能获得一个临时令牌,用于针对 API 控制器进行身份验证。
我正在进行的项目是使用运行我编写的自定义 UWP 应用程序的 Windows IOT 设备,该应用程序需要在后台连接到此 API 以记录数据并提取最新的设备配置。
我曾计划为每台设备提供一个用于身份验证的唯一令牌,该令牌将在初始设备/应用程序设置期间输入和存储。我使用过的大多数第三方 API 只会向您颁发一个永久令牌,您可以使用它来访问他们的 API。我想做类似的事情。
【问题讨论】:
标签:
authentication
asp.net-core
.net-core
asp.net-core-webapi
【解决方案1】:
对于我的目的而言,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();到我的创业班