【问题标题】:.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();到我的创业班

【讨论】:

    【解决方案2】:

    您可以使用标准 JWT 方法,在用户名/密码登录时创建两个令牌。

    第一个令牌(访问令牌)是短暂的,包含访问您的业务登录端点的权限。第二个(刷新令牌)是永久的,允许您获取一个新的访问令牌,一旦它过期,创建一个连续的访问模式。刷新令牌应该只带有 refresh 声明,这将允许您访问专门用于创建新的短期令牌的端点。

    那里有大量的教程,比如http://piotrgankiewicz.com/2017/12/07/jwt-refresh-tokens-and-net-core/

    【讨论】:

      猜你喜欢
      • 2020-02-05
      • 2018-01-07
      • 1970-01-01
      • 2012-09-12
      • 2020-06-05
      • 1970-01-01
      • 2019-07-17
      • 2021-01-13
      • 2017-10-30
      相关资源
      最近更新 更多