-
Notifications
You must be signed in to change notification settings - Fork 1
4. Authentication
Maciej Chmiel edited this page Feb 8, 2023
·
3 revisions
With SAPI, it couldn't be easier!
Today we will be extending our Weather API and put the data behind an API key.
- Basic knowledge of C#
- Basic knowledge of SAPI(from previous Tutorial)
- (optionally) REST Client (Postman, Insomnia)
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;
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;
}
...