From 0210ab449f7546a90982a8cb28403f3d6af02230 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 21 Jan 2021 23:07:53 -0600 Subject: refactor login to use configured users --- src/slskd/Controllers/SessionController.cs | 39 +++++++++++++++++++++++------- 1 file changed, 30 insertions(+), 9 deletions(-) (limited to 'src/slskd/Controllers/SessionController.cs') diff --git a/src/slskd/Controllers/SessionController.cs b/src/slskd/Controllers/SessionController.cs index 5c162708..df523b75 100644 --- a/src/slskd/Controllers/SessionController.cs +++ b/src/slskd/Controllers/SessionController.cs @@ -8,6 +8,8 @@ using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using slskd.DTO; + using Microsoft.Extensions.Options; + using System.Linq; /// /// Session @@ -19,8 +21,18 @@ [Consumes("application/json")] public class SessionController : ControllerBase { - public SessionController() + private IOptionsSnapshot SoulseekOptions { get; set; } + private IOptionsSnapshot AuthenticationOptions { get; set; } + private SymmetricSecurityKey JwtSigningKey { get; set; } + + public SessionController( + IOptionsSnapshot soulseekOptions, + IOptionsSnapshot authenticationOptions, + SymmetricSecurityKey jwtSigningKey) { + SoulseekOptions = soulseekOptions; + AuthenticationOptions = authenticationOptions; + JwtSigningKey = jwtSigningKey; } /// @@ -83,29 +95,38 @@ return BadRequest("Username and/or Password missing or invalid"); } - if (login.Username == Startup.Username && login.Password == Startup.Password) + var user = AuthenticationOptions.Value.Users + .Where(u => u.Name == login.Username) + .FirstOrDefault(); + + if (user == default) + { + return Unauthorized(); + } + + if (login.Password == user.Password) { - return Ok(new TokenResponse(GetJwtSecurityToken())); + return Ok(new TokenResponse(GetJwtSecurityToken(user.Name, user.Role))); } return Unauthorized(); } - private JwtSecurityToken GetJwtSecurityToken() + private JwtSecurityToken GetJwtSecurityToken(string username, Role role) { var issuedUtc = DateTime.UtcNow; - var expiresUtc = DateTime.UtcNow.AddMilliseconds(Startup.SecurityTokenTTL); + var expiresUtc = DateTime.UtcNow.AddMilliseconds(Program.JwtTTL); var claims = new List() { - new Claim(ClaimTypes.Name, Startup.Username), + new Claim(ClaimTypes.Name, username), new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()), - new Claim(ClaimTypes.Role, "User"), - new Claim("name", Startup.Username), + new Claim(ClaimTypes.Role, role.ToString()), + new Claim("name", username), new Claim("iat", ((DateTimeOffset)issuedUtc).ToUnixTimeSeconds().ToString()) }; - var credentials = new SigningCredentials(Startup.JwtSigningKey, SecurityAlgorithms.HmacSha256); + var credentials = new SigningCredentials(JwtSigningKey, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: "slskd", -- cgit v1.2.3