Skip to content

4. Authentication

Maciej Chmiel edited this page Feb 8, 2023 · 3 revisions

Wanna hide something behind a paywall? Or maybe defend your secrets from prying eyes?

With SAPI, it couldn't be easier!

What are we building today?

Today we will be extending our Weather API and put the data behind an API key.

Prerequisites

Step 1 - Create a list of keys in our mock database

This mock database is something like a guest list for a club - only the people that are on that list can enter, but instead of people we have keys!

// Services/Database.cs
...
private static List<string> authKeys = new()
{
	"295cf53e459472a116259cf6f8ee95e8",
	"598fc640a8be4f51618dfb8a0548e4ce",
	"d2af577974f50a125dbfa582820c764b",
	"b5ecfd59a8aa754b48d055de87f717b2",
	"6f44172d87f4e0d81930b076538872c6",
	"baeb98fff00c37df48222bf53bab0cfb",
	"d9684d77c454a7bd940647a9ce2eabc5",
	"9c58dc21d99263036100291836fe339e",
	"1c6fe9027a6cb57721aa1cd3d9442535",
	"3ac8fdcca1fe56f9a7004b2dcb8f81b5"
};

...
public static List<string> GetKeys() => authKeys;

Step 2 - Check if user is authenticated

In your endpoint before we get any data from database check if user is autenticated, and if not return 401 (Unauthorized).

// Endpoints/GetWeather.cs
using SAPI.Utilities.Auth;
...
if (!Auth.CheckForKey(Database.GetKeys(), "x-api-key", ref request))
{
	Utilities.Error(HttpStatus.Unauthorized, ref response);
	return;
}
...

Step 3 - check the results: with and without specifying a key in the request.