Added basic auth checking code. First bit of code to protect an API call in the Employee controller.

This commit is contained in:
2021-01-03 18:44:08 -06:00
parent 26ea8e8cbc
commit ddb42da7bb
15 changed files with 670 additions and 15 deletions
+55 -9
View File
@@ -5,6 +5,7 @@ using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SecureCore.Services;
namespace SecureCore.Controllers
{
@@ -16,20 +17,65 @@ namespace SecureCore.Controllers
[AcceptVerbs("POST")]
public IActionResult Login(LoginInfo info)
{
var (hash, salt) = Authentication.HashPassword(info.Password);
var options = new CookieOptions
var (password, saltHash) = UserDataService.GetUserPasswordHash(info.UserName);
if (Authentication.PasswordIsValid(info.Password, saltHash, password))
{
Domain = "copyrightcrusader.org",
if (HttpContext.Request.Cookies.ContainsKey("Session"))
{
if(UserDataService.IsSessionTokenValid(HttpContext.Request.Cookies["Session"]))//, info.UserName))
return Ok($"Session is live{Environment.NewLine}");
}
var sessionToken = Authentication.CreateSessionToken();
UserDataService.SetUserSessionToken(UserDataService.GetUserId(info.UserName), sessionToken, DateTime.Now.AddDays(7));
HttpContext.Response.Cookies.Append("Session", sessionToken, GetCookieOptions());
return Ok($"Logged in success{Environment.NewLine}");
}
else
{
return Unauthorized();
}
}
[HttpPost("Register")]
[AcceptVerbs("POST")]
public IActionResult Register(LoginInfo info)
{
var (hash, salt) = Authentication.HashPassword(info.Password);
var sessionToken = Authentication.CreateSessionToken();
try
{
var i = UserDataService.RegisterNewUser(info.UserName, info.Email, hash, salt, sessionToken, DateTime.Now.AddDays(7));
HttpContext.Response.Cookies.Append("Session", sessionToken, GetCookieOptions());
return Ok($"New User ID: {i}");
}
catch (Exception e)
{
return Unauthorized(e.Message);
}
}
private CookieOptions GetCookieOptions()
{
return new CookieOptions
{
//Domain = "copyrightcrusader.org",
Expires = DateTime.Now.AddDays(7),
HttpOnly = true,
Secure = true,
//HttpOnly = true,
//Secure = true,
Path = "/",
SameSite = SameSiteMode.Strict
};
HttpContext.Response.Cookies.Append("Session", Authentication.CreateSessionToken(), options);
return Ok();
}
}
//TODO: Read more https://www.valentinog.com/blog/cookies/
// And this https://blog.webf.zone/ultimate-guide-to-http-cookies-2aa3e083dbae
}
+8 -2
View File
@@ -25,13 +25,19 @@ namespace SecureCore.Controllers
[HttpGet]
public IActionResult Get()
{
return Ok(DataService.Get());
if (Authentication.IsAllowed(HttpContext))
return Ok(DataService.Get());
else
return Unauthorized();
}
[HttpGet("{id}", Name = "Get")]
public IActionResult Get(int id)
{
return Ok(DataService.GetById(id));
if (Authentication.IsAllowed(HttpContext))
return Ok(DataService.GetById(id));
else
return Unauthorized();
}
}