using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Threading.Tasks; using LCU.Library.Internal.Security.Models.AuthRequest; using LCU.Library.Internal.Security.Service; using Microsoft.AspNetCore.Mvc; using NUnit.Framework; namespace LCU.Library.Internal.SecurityTests.Service { public class UsernamePasswordAuthorizationServiceTest { private readonly IUsernamePasswordAuthorizationService _service; private readonly FakeAzureAdVerificationService _activeDirectoryService = new FakeAzureAdVerificationService(); public UsernamePasswordAuthorizationServiceTest() { _service = new UsernamePasswordAuthorizationService(_activeDirectoryService); } [Test] public async Task OnAuthorizationAsync_NullJWTFromAd_ReturnsUnauthorized() { var authResult = await _service.OnAuthorizationAsync(AuthRequestFactory()); Assert.IsInstanceOf(authResult); } [Test] public async Task OnAuthorizationAsync_JWTNotAuthorizedByRole_ReturnsForbidden() { var request = AuthRequestFactory(); _activeDirectoryService.SetAuthenticable(request.UserName, request.Password); var authResult = await _service.OnAuthorizationAsync(request); Assert.IsInstanceOf(authResult); } [Test] public async Task OnAuthorizationAsync_JWTAuthorized_ReturnsNull() { var request = AuthRequestFactory(); _activeDirectoryService.SetAuthenticable(request.UserName, request.Password); _activeDirectoryService.SetAuthorized(request.UserName, request.Password); var authResult = await _service.OnAuthorizationAsync(request); Assert.IsNull(authResult); } private static AuthRequest AuthRequestFactory() => new AuthRequest { UserName = Guid.NewGuid().ToString(), Password = Guid.NewGuid().ToString() }; private class FakeAzureAdVerificationService : IAzureAdVerificationService { private readonly IDictionary> _tokens = new Dictionary>(); private readonly IList _authorizedTokens = new List(); public void SetAuthenticable(string userName, string password) { if (_tokens.TryGetValue(userName, out var userPasswords)) { userPasswords[password] = new JwtSecurityToken(); } else { _tokens[userName] = new Dictionary { [password] = new JwtSecurityToken() }; } } public void SetAuthorized(string userName, string password) { _authorizedTokens.Add(_tokens[userName][password]); } public Task GetTokenForWebApiUsingUsernamePasswordAsync(string userName, string password) { return Task.FromResult ( _tokens.TryGetValue(userName, out var userPassword) ? userPassword.TryGetValue(password, out var token) ? token : null : null ); } public bool ValidateJwtHasAuthorizedRole(JwtSecurityToken jsonToken) { return _authorizedTokens.Contains(jsonToken); } public bool ValidateJwtHasAuthorizedRole(JwtSecurityToken jsonToken, List approvedRoles) { return _authorizedTokens.Contains(jsonToken); } } } }