Skip to content

Commit

Permalink
Merge pull request #162 from kolappannathan/dev
Browse files Browse the repository at this point in the history
v8.0.0
  • Loading branch information
kolappannathan committed Dec 2, 2023
2 parents e7336ce + 2aecde4 commit 16e17af
Show file tree
Hide file tree
Showing 17 changed files with 65 additions and 79 deletions.
1 change: 1 addition & 0 deletions .vscode/spellright.dict
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ launchsettings.json
editorconfig
db
Serilog
Bcrypt
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,21 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).

## [Unreleased]

## [8.0.0] - 2023-12-02
### Added
- Salt added as separate param for Bcrypt in Security lib. Previously it was indented to be already added and sent with the plain text password.
- New test cases in postman

### Changed
- Updated .NET version to 8
- Moved Configurators into a separate folder to simplify Program.cs
- Updated Random String Generator to use `System.Security.Cryptography.RandomNumberGenerator`.
- Using updated checks for Argument exceptions
- Updated dependencies

### Removed
- Removed the random number generating function. The built-in function with RandomNumberGenerator to be used instead.

## [7.1.0] - 2023-03-02
### Added
- Added interfaces for library classes, helper functions.
Expand Down
4 changes: 2 additions & 2 deletions src/WebApiBolierplate/API/API.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

Expand All @@ -13,7 +13,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.14" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.0" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup>
Expand Down
4 changes: 2 additions & 2 deletions src/WebApiBolierplate/API/Models/LoginDTO.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ public LoginDTO()

}

[Required(ErrorMessage = "No name. No game.")]
[Required(ErrorMessage = "No name. No game.", AllowEmptyStrings = false)]
public string UserName { get; set; }

[Required(ErrorMessage = "No password?! Are you kidding?")]
[Required(ErrorMessage = "No password?! Are you kidding?", AllowEmptyStrings = false)]
public string Password { get; set; }
}
2 changes: 1 addition & 1 deletion src/WebApiBolierplate/API/appsettings.Development.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"JWT": {
"Audience": "https://www.example.com",
"Issuer": "WebApiBoilerplate",
"Key": "This is a JWT secret key",
"Key": "JWT_keys_with_random_chars---m4sjcv46v06etirgflvcgdwixb9tg5wk5hy1mew85zcznjshivssia9mls539rsq",
"HoursValid": 48
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/WebApiBolierplate/API/appsettings.production.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"JWT": {
"Audience": "https://www.example.com",
"Issuer": "WebApiBoilerplate",
"Key": "This is a JWT secret key",
"Key": "JWT_keys_with_random_chars---9sav3zkqd1gmgur2r7sdxqwtwvsxong36lylhdnwca3sfr5n6kqg7qpdr1nbhf1q",
"HoursValid": 48
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/WebApiBolierplate/Core.Constants/Core.Constants.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>

</Project>
2 changes: 1 addition & 1 deletion src/WebApiBolierplate/Core.Lib/Core.Lib.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,4 @@ public interface IRandomUtils
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
public string GenRandomChar(int length, CharSet charSet);


/// <summary>
/// Generates a random number using cryptography within the specified range
/// Ref: https://stackoverflow.com/a/38669162/5407188
/// </summary>
/// <param name="min">minimum value for the random number</param>
/// <param name="max">maximum value for the random number</param>
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
public int GenRandomNumber(int min, int max);
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,20 @@ public interface ISecurityUtils
/// Hashes the plaintext password using BCrypt and returns the hash
/// </summary>
/// <param name="plainText"></param>
/// <param name="salt"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentException"></exception>
public string HashBCrypt(string plainText);
public string HashBCrypt(string plainText, string salt);

/// <summary>
/// Verfies the hash and password with Brcypt
/// </summary>
/// <param name="plainText"></param>
/// <param name="salt"></param>
/// <param name="hash"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentException"></exception>
public bool VerifyBCrypt(string plainText, string hash);
public bool VerifyBCrypt(string plainText, string salt, string hash);
}
6 changes: 1 addition & 5 deletions src/WebApiBolierplate/Core.Lib/Utilities/JwtUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,7 @@ public string GenerateToken()
private void EnsureArguments()
{
ArgumentNullException.ThrowIfNull(_securityKey);

if (_expiryInHours == 0)
{
throw new ArgumentNullException("Expiry Time");
}
ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(_expiryInHours, 0);
}

/// <summary>
Expand Down
45 changes: 7 additions & 38 deletions src/WebApiBolierplate/Core.Lib/Utilities/RandomUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ public sealed class RandomUtils : IRandomUtils
{
#region [Declarations]

private string _uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private string _lowercase = "abcdefghijklmnopqrstuvwxyz";
private string _numbers = "0123456789";
private readonly string _uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private readonly string _lowercase = "abcdefghijklmnopqrstuvwxyz";
private readonly string _numbers = "0123456789";

#endregion Declarations

Expand Down Expand Up @@ -58,42 +58,11 @@ private char[] GetChars(CharSet charSet)

public string GenRandomChar(int length, CharSet charSet)
{
if (length <= 0)
{
throw new ArgumentException("length", "Length of the random character must be greater than zero");
}

char[] chars = GetChars(charSet);
var stringChars = new char[length];

for (int i = 0; i < length; i++)
{
stringChars[i] = chars[GenRandomNumber(0, chars.Length)];
}

var finalString = new String(stringChars);
return finalString;
}
ArgumentOutOfRangeException.ThrowIfLessThan(length, 1);

public int GenRandomNumber(int min, int max)
{
if (min >= max)
{
throw new ArgumentException("The value of min should be less than max");
}

using (var generator = RandomNumberGenerator.Create())
{
// Generate four random bytes
var four_bytes = new byte[4];
generator.GetBytes(four_bytes);

// Convert the bytes to a UInt32
var scale = BitConverter.ToUInt32(four_bytes, 0);

// And use that to pick a random number >= min and < max
return (int)(min + (max - min) * (scale / (uint.MaxValue + 1.0)));
}
var chars = GetChars(charSet);
var stringChars = RandomNumberGenerator.GetString(chars, length);
return new string(stringChars);
}

#endregion [Public Functions]
Expand Down
10 changes: 6 additions & 4 deletions src/WebApiBolierplate/Core.Lib/Utilities/SecurityUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,20 +60,22 @@ public string DecryptString(string cipherText, string encryptionKey)
}
}

public string HashBCrypt(string plainText)
public string HashBCrypt(string plainText, string salt)
{
ArgumentException.ThrowIfNullOrEmpty(plainText);
ArgumentException.ThrowIfNullOrEmpty(salt);

var hash = BCrypt.Net.BCrypt.HashPassword(plainText, workFactor: 10);
var hash = BCrypt.Net.BCrypt.HashPassword(plainText + salt, workFactor: 10);
return hash;
}

public bool VerifyBCrypt(string plainText, string hash)
public bool VerifyBCrypt(string plainText, string salt, string hash)
{
ArgumentException.ThrowIfNullOrEmpty(plainText);
ArgumentException.ThrowIfNullOrEmpty(salt);
ArgumentException.ThrowIfNullOrEmpty(hash);

var isMatch = BCrypt.Net.BCrypt.Verify(plainText, hash);
var isMatch = BCrypt.Net.BCrypt.Verify(plainText + salt, hash);
return isMatch;
}
}
2 changes: 1 addition & 1 deletion src/WebApiBolierplate/Core.Test/Core.Test.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>

<IsPackable>false</IsPackable>
</PropertyGroup>
Expand Down
12 changes: 4 additions & 8 deletions src/WebApiBolierplate/Core.Test/Utilities/RandomUtilsTest.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Core.Lib.Utilities;
using Core.Lib.Utilities.Interfaces;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace Core.Test.Utilities;

Expand All @@ -20,14 +21,9 @@ public void TestingRandomChar()
const int length = 10;
var randomChars = _randomUtils.GenRandomChar(length, Constants.Enums.CharSet.Alphabets);
Assert.AreEqual(randomChars.Length, length);
}

[TestMethod]
public void TestRandomNo()
{
const int min = 0, max = 108;
var randomChars = _randomUtils.GenRandomNumber(min, max);
Assert.IsTrue(randomChars <= max);
Assert.IsTrue(randomChars >= min);
Assert.ThrowsException<ArgumentOutOfRangeException>(() => {
_randomUtils.GenRandomChar(0, Constants.Enums.CharSet.Alphabets);
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ public sealed class SecurityUtilsTest
private readonly ISecurityUtils _securityUtils;
private const string _sampleString = "This is a sample string";
private const string _key = "THk5emRHRmphMjkyWlhKbWJHOTNMbU52YlM5eGRXVnpkR2x2Ym5Ndk16azJORGs1TnpZdmFYTXRh";
private const string _salt = "umssxcahqnumssxcahqnumssxcahqn";

public SecurityUtilsTest()
{
Expand All @@ -20,8 +21,8 @@ public SecurityUtilsTest()
public void TestHash()
{

var hashedValue = _securityUtils.HashBCrypt(_sampleString);
var hashComparission = _securityUtils.VerifyBCrypt(_sampleString, hashedValue);
var hashedValue = _securityUtils.HashBCrypt(_sampleString, _salt);
var hashComparission = _securityUtils.VerifyBCrypt(_sampleString, _salt, hashedValue);
Assert.IsTrue(hashComparission);
}

Expand Down
15 changes: 15 additions & 0 deletions src/postman/Web API Boilerplate.postman_collection.json
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,11 @@
"exec": [
"pm.test(\"Status code is 401\", function () {\r",
" pm.response.to.have.status(401);\r",
"});\r",
"\r",
"pm.test(\"Check error message\", function () {\r",
" var jsonData = pm.response.json();\r",
" pm.expect(jsonData.message).to.eql(\"The credentials are invalid.\");\r",
"});"
],
"type": "text/javascript"
Expand Down Expand Up @@ -235,6 +240,11 @@
"exec": [
"pm.test(\"Status code is 500\", function () {\r",
" pm.response.to.have.status(500);\r",
"});\r",
"\r",
"pm.test(\"Check Error msg\", function () {\r",
" var jsonData = pm.response.json();\r",
" pm.expect(jsonData.message).to.eql(\"Oops! An Internal Error Occured.\");\r",
"});"
],
"type": "text/javascript"
Expand Down Expand Up @@ -274,6 +284,11 @@
"exec": [
"pm.test(\"Status code is 400\", function () {\r",
" pm.response.to.have.status(400);\r",
"});\r",
"\r",
"pm.test(\"Check error message\", function () {\r",
" var jsonData = pm.response.json();\r",
" pm.expect(jsonData.message).to.eql(\"No name. No game.\");\r",
"});"
],
"type": "text/javascript"
Expand Down

0 comments on commit 16e17af

Please sign in to comment.