Skip to content

Commit

Permalink
Merge pull request #5 from Maciejowski2006/auth
Browse files Browse the repository at this point in the history
Created authorization
  • Loading branch information
Maciejowski2006 authored Dec 6, 2022
2 parents 47117f2 + fcbbd8d commit ff39d58
Show file tree
Hide file tree
Showing 6 changed files with 92 additions and 6 deletions.
1 change: 0 additions & 1 deletion GettingStarted_WeatherAPI/Endpoints/GetWeather.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
using WeatherAPI.Models;
using WeatherAPI.Services;


namespace WeatherAPI.Endpoints;

public class GetWeather : IEndpoint
Expand Down
4 changes: 1 addition & 3 deletions SAPI/Config.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,11 @@ public static void Init()
if (File.Exists(configFile))
{
if (ReadConfig().ConfigVersion != new ConfigFile().ConfigVersion)
{
CreateConfig(true);
}

return;
}
CreateConfig();

}
private static void CreateConfig(bool update = false)
{
Expand Down
4 changes: 2 additions & 2 deletions SAPI/SAPI.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@
<Copyright>Copyright © Maciejowski 2022</Copyright>
<PackageLicenseUrl>https://github.com/Maciejowski2006/SAPI/blob/master/LICENSE.md</PackageLicenseUrl>
<RepositoryUrl>https://github.com/Maciejowski2006/SAPI</RepositoryUrl>
<PackageVersion>4.0.0</PackageVersion>
<PackageVersion>5.0.0</PackageVersion>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.2" />
</ItemGroup>

</Project>
61 changes: 61 additions & 0 deletions SAPI/Utilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ public enum HttpStatus
BadGateway,
ServiceUnavailable
}
public record BasicAuthCredentials(string username, string password);

public class Utilities
{
private static Dictionary<HttpStatus, string> httpStatusNames = new()
Expand Down Expand Up @@ -136,4 +138,63 @@ public static void Error(HttpStatus httpStatus, ref HttpListenerResponse respons

response.OutputStream.Write(data, 0, data.Length);
}

/// <summary>
/// Checks if user with provided API key exists.
/// </summary>
/// <param name="keys">List of all API keys authorized</param>
/// <param name="headerName">Name of the authorization header(the OpenAPI 3.0 specification says the default should be "X-Api-Key"</param>
/// <param name="request">Request ref you got from server - argument in Task()</param>
public static bool CheckForKeyAuthorization(List<string> keys, string headerName, ref HttpListenerRequest request)
{
try
{
foreach (string key in keys)
{
if (request.Headers.Get(headerName).Contains(key))
return true;
}
return false;
}
catch
{
Console.WriteLine($"Request does not have {headerName}.");
return false;
}
}
/// <summary>
/// Checks if user with provided credentials exists.
/// </summary>
/// <param name="credentialsList">List of all usernames and passwords authorized</param>
/// <param name="request">Request ref you got from server - argument in Task()</param>
public static bool CheckForUserPassAuthorization(List<BasicAuthCredentials> credentialsList, ref HttpListenerRequest request)
{
try
{
if (request.Headers.Get("Authorization").Contains("Basic "))
{
// Get data from header end remove "Basic " at the beginning
string authData = request.Headers.GetValues("Authorization").GetValue(0).ToString().Substring(6);

// Convert from Base64
byte[] decodedBase64 = Convert.FromBase64String(authData);

// Encode in UTF-8
string[] auth = Encoding.UTF8.GetString(decodedBase64).Split(':');
BasicAuthCredentials userCredentials = new BasicAuthCredentials(auth[0], auth[1]);

foreach (BasicAuthCredentials credentials in credentialsList)
{
if (String.Equals(userCredentials.username, credentials.username) && String.Equals(userCredentials.password, credentials.password))
return true;
}
}
}
catch
{
Console.WriteLine($"Request does not have Authorization header.");
return false;
}
return false;
}
}
27 changes: 27 additions & 0 deletions SAPI_Testing/Endpoints/ApiAuth.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using System.Net;
using SAPI.Endpoints;
using SAPI.Utilities;

namespace Testing.Endpoints;

public class ApiAuth : IEndpoint
{

public string url { get; } = "auth";
public Method method { get; } = Method.GET;
public void Task(ref HttpListenerRequest request, ref HttpListenerResponse response, Dictionary<string, string> parameters)
{
List<BasicAuthCredentials> credentials = new ()
{
new BasicAuthCredentials("dub", "iel"),
new BasicAuthCredentials("user", "pass"),
new BasicAuthCredentials("user", "inny"),

};
bool keyAuth = Utilities.CheckForKeyAuthorization(new List<string>() {"api", "bruh", "duh"}, "x-api-key", ref request);
bool userPassAuth = Utilities.CheckForUserPassAuthorization(credentials, ref request);

Console.WriteLine($"Key Auth: {keyAuth}");
Console.WriteLine($"User+Password Auth: {userPassAuth}");
}
}
1 change: 1 addition & 0 deletions SAPI_Testing/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ public static void Main()
sapi.MountEndpoint(new SendJson());
sapi.MountEndpoint(new DynamicGet());
sapi.MountEndpoint(new Html());
sapi.MountEndpoint(new ApiAuth());

sapi.Start();
}
Expand Down

0 comments on commit ff39d58

Please sign in to comment.