I have been looking at tutorial after tutorial about securing your .NET Core WebAPI with authentication tokens and everything seems to require a username/password combo in order to get a temporary token for use to authenticate against API controllers.
The project I am working on is using Windows IOT devices running a custom UWP application I wrote that needs to connect to this API in the background in order to record data and pull down the latest device configurations.
I had planned on giving each device a unique token for authenticating that will be entered and stored during the initial device/app setup. Most third party APIs I have worked with just issue you a permanent token that you can use to access their APIs. I was wanting to do something similar.
JWT seemed overkill and overly complex for my purposes so I ended up going with a middleware solution by following this tutorial: https://www.youtube.com/watch?v=n0llyujNGw8
I ended up creating a middleware class with the following code:
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>();
    }
}
Then I just added app.UseTokenAuth(); to my Startup class
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With