public async Task GetRecursoQuery_Handle()
    {
        // Arrange
        IUnitOfWork          unitOfWork = DbContextHelper.GetContext();
        IMapper              mapper     = AutoMapperHelper.GetMappings();
        ICryptographyManager manager    = CryptographyHelper.GetInstance();

        Guid recursoId = Guid.NewGuid();

        await unitOfWork.RecursoRepository.AddAsync(MockEntityHelper.GetNewRecurso(recursoId));

        await unitOfWork.SaveChangesAsync();

        GetRecursoQuery request = new()
        {
            Id = recursoId
        };

        // Act
        RecursoHandler   handler  = new(unitOfWork, mapper, manager);
        RecursoViewModel response = await handler.Handle(request, CancellationToken.None);

        // Assert
        Assert.True(response != null);
        Assert.True(response.Id != Guid.Empty);
        Assert.True(response.DataInclusao.Ticks != 0);
        Assert.True(response.Senha == null);
        Assert.True(response.Salt == null);
    }
    public async Task ListRecursoQuery_Handle()
    {
        // Arrange
        IUnitOfWork          unitOfWork = DbContextHelper.GetContext();
        IMapper              mapper     = AutoMapperHelper.GetMappings();
        ICryptographyManager manager    = CryptographyHelper.GetInstance();

        Guid recursoId = Guid.NewGuid();

        await unitOfWork.RecursoRepository.AddAsync(MockEntityHelper.GetNewRecurso(recursoId));

        await unitOfWork.RecursoRepository.AddAsync(MockEntityHelper.GetNewRecurso());

        await unitOfWork.RecursoRepository.AddAsync(MockEntityHelper.GetNewRecurso());

        await unitOfWork.SaveChangesAsync();

        ListRecursoQuery request = new();

        // Act
        RecursoHandler handler = new(unitOfWork, mapper, manager);
        IEnumerable <RecursoViewModel> response = await handler.Handle(request, CancellationToken.None);

        // Assert
        Assert.True(response != null);
        Assert.True(response.Any());
        Assert.True(response.FirstOrDefault(x => x.Id == recursoId) != null);
    }
        public static Dictionary <string, string> CreateClientCredentialBodyParameters(
            ICoreLogger logger,
            ICryptographyManager cryptographyManager,
            ClientCredentialWrapper clientCredential,
            string clientId,
            AuthorityEndpoints endpoints,
            bool sendX5C)
        {
            Dictionary <string, string> parameters = new Dictionary <string, string>();

            if (clientCredential != null)
            {
                if (clientCredential.AuthenticationType == ConfidentialClientAuthenticationType.ClientSecret)
                {
                    parameters[OAuth2Parameter.ClientSecret] = clientCredential.Secret;
                }
                else
                {
                    if ((clientCredential.CachedAssertion == null || clientCredential.ValidTo != 0) && clientCredential.AuthenticationType != ConfidentialClientAuthenticationType.SignedClientAssertion)
                    {
                        if (!ValidateClientAssertion(clientCredential, endpoints, sendX5C))
                        {
                            logger.Info(LogMessages.ClientAssertionDoesNotExistOrNearExpiry);

                            JsonWebToken jwtToken;

                            if (clientCredential.AuthenticationType == ConfidentialClientAuthenticationType.ClientCertificateWithClaims)
                            {
                                jwtToken = new JsonWebToken(cryptographyManager, clientId, endpoints?.SelfSignedJwtAudience, clientCredential.ClaimsToSign, clientCredential.AppendDefaultClaims);
                            }
                            else
                            {
                                jwtToken = new JsonWebToken(cryptographyManager, clientId, endpoints?.SelfSignedJwtAudience);
                            }

                            clientCredential.CachedAssertion = jwtToken.Sign(clientCredential, sendX5C);
                            clientCredential.ValidTo         = jwtToken.ValidTo;
                            clientCredential.ContainsX5C     = sendX5C;
                            clientCredential.Audience        = endpoints?.SelfSignedJwtAudience;
                        }
                        else
                        {
                            logger.Info(LogMessages.ReusingTheUnexpiredClientAssertion);
                        }
                    }

                    parameters[OAuth2Parameter.ClientAssertionType] = OAuth2AssertionType.JwtBearer;

                    if (clientCredential.AuthenticationType == ConfidentialClientAuthenticationType.SignedClientAssertion)
                    {
                        parameters[OAuth2Parameter.ClientAssertion] = clientCredential.SignedAssertion;
                    }
                    else
                    {
                        parameters[OAuth2Parameter.ClientAssertion] = clientCredential.CachedAssertion;
                    }
                }
            }
            return(parameters);
        }
        /// <summary>
        /// The strict thumbprint is based on:
        /// ClientId
        /// Authority (env + tenant)
        /// Scopes
        /// hash(RT) or UPN for IWA (not supported)
        /// </summary>
        private static string GetRequestStrictThumbprint(
            IReadOnlyDictionary <string, string> bodyParams,
            string authority,
            ICryptographyManager crypto)
        {
            StringBuilder sb = new StringBuilder();

            if (bodyParams.TryGetValue(OAuth2Parameter.ClientId, out string clientId))
            {
                sb.Append((clientId ?? "") + ThrottleCommon.KeyDelimiter);
            }
            sb.Append(authority + ThrottleCommon.KeyDelimiter);
            if (bodyParams.TryGetValue(OAuth2Parameter.Scope, out string scopes))
            {
                sb.Append((scopes ?? "") + ThrottleCommon.KeyDelimiter);
            }

            if (bodyParams.TryGetValue(OAuth2Parameter.RefreshToken, out string rt) &&
                !string.IsNullOrEmpty(rt))
            {
                sb.Append(crypto.CreateSha256Hash(rt) + ThrottleCommon.KeyDelimiter);
            }

            return(sb.ToString());
        }
 public RecursoController(IUnitOfWork unitOfWork,
                          ICryptographyManager cryptographyManager,
                          IConfiguration configuration)
 {
     _unitOfWork          = unitOfWork;
     _cryptographyManager = cryptographyManager;
     _configuration       = configuration;
 }
Example #6
0
 public ApiEvent(
     ICoreLogger logger,
     ICryptographyManager cryptographyManager,
     string correlationId) : base(EventNamePrefix + "api_event", correlationId)
 {
     _logger = logger;
     _cryptographyManager = cryptographyManager;
 }
Example #7
0
 public void Initialize()
 {
     TestCommon.ResetInternalStaticCaches();
     _serviceBundle = TestCommon.CreateServiceBundleWithCustomHttpManager(null, clientId: ClientId);
     _logger        = _serviceBundle.ApplicationLogger;
     _platformProxy = _serviceBundle.PlatformProxy;
     _crypto        = _platformProxy.CryptographyManager;
 }
 public void Initialize()
 {
     TestCommon.ResetInternalStaticCaches();
     _myReceiver       = new MyReceiver();
     _serviceBundle    = TestCommon.CreateServiceBundleWithCustomHttpManager(null, clientId: ClientId);
     _logger           = _serviceBundle.DefaultLogger;
     _platformProxy    = _serviceBundle.PlatformProxy;
     _crypto           = _platformProxy.CryptographyManager;
     _telemetryManager = new TelemetryManager(_serviceBundle.Config, _platformProxy, _myReceiver.HandleTelemetryEvents);
 }
Example #9
0
        public SecurityManager(IUsers userDataAccess, ICryptographyManager cryptographyManager, IUsers users)
        {
            if (userDataAccess == null) throw new ArgumentNullException("userDataAccess");
            if (cryptographyManager == null) throw new ArgumentNullException("cryptographyManager");
            if (users == null) throw new ArgumentNullException("users");

            _dataAccess = userDataAccess;
            _cryptographyManager = cryptographyManager;
            _users = users;
        }
        public JsonWebToken(ICryptographyManager cryptographyManager, string clientId, string audience)
        {
            _cryptographyManager = cryptographyManager;
            DateTime validFrom = DateTime.UtcNow;

            Payload = new JWTPayload
            {
                Audience      = audience,
                Issuer        = clientId,
                ValidFrom     = ConvertToTimeT(validFrom),
                ValidTo       = ConvertToTimeT(validFrom + TimeSpan.FromSeconds(JsonWebTokenConstants.JwtToAadLifetimeInSeconds)),
                Subject       = clientId,
                JwtIdentifier = Guid.NewGuid().ToString()
            };
        }
Example #11
0
        public UapTokenCacheAccessor(ICryptographyManager cryptographyManager)
        {
            _cryptographyManager = cryptographyManager;
            var localSettings = ApplicationData.Current.LocalSettings;

            _accessTokenContainer =
                localSettings.CreateContainer(LocalSettingsTokenContainerName, ApplicationDataCreateDisposition.Always);
            _refreshTokenContainer =
                localSettings.CreateContainer(LocalSettingsRefreshTokenContainerName,
                                              ApplicationDataCreateDisposition.Always);
            _idTokenContainer =
                localSettings.CreateContainer(LocalSettingsIdTokenContainerName,
                                              ApplicationDataCreateDisposition.Always);
            _accountContainer =
                localSettings.CreateContainer(LocalSettingsAccountContainerName,
                                              ApplicationDataCreateDisposition.Always);
        }
    public async Task CreateRecursoCommand_Handle()
    {
        // Arrange
        IUnitOfWork          unitOfWork = DbContextHelper.GetContext();
        IMapper              mapper     = AutoMapperHelper.GetMappings();
        ICryptographyManager manager    = CryptographyHelper.GetInstance();

        CreateRecursoCommand request = new()
        {
            Recurso = MockViewModelHelper.GetNewRecurso()
        };

        // Act
        RecursoHandler  handler  = new(unitOfWork, mapper, manager);
        OperationResult response = await handler.Handle(request, CancellationToken.None);

        // Assert
        Assert.True(response == OperationResult.Success);
    }
    public async Task UpdateRecursoCommand_Handle()
    {
        // Arrange
        IUnitOfWork          unitOfWork = DbContextHelper.GetContext();
        IMapper              mapper     = AutoMapperHelper.GetMappings();
        ICryptographyManager manager    = CryptographyHelper.GetInstance();

        Guid     recursoId    = Guid.NewGuid();
        DateTime dataInclusao = DateTime.Now;

        Recurso recurso = MockEntityHelper.GetNewRecurso(recursoId);

        await unitOfWork.RecursoRepository.AddAsync(recurso);

        await unitOfWork.SaveChangesAsync();

        unitOfWork.RecursoRepository.Detatch(recurso);

        UpdateRecursoCommand request = new()
        {
            Recurso = MockViewModelHelper.GetNewRecurso(recursoId, dataInclusao)
        };

        GetRecursoQuery request2 = new()
        {
            Id = recursoId
        };

        // Act
        RecursoHandler  handler  = new(unitOfWork, mapper, manager);
        OperationResult response = await handler.Handle(request, CancellationToken.None);

        RecursoViewModel response2 = await handler.Handle(request2, CancellationToken.None);

        // Assert
        Assert.True(response == OperationResult.Success);
        Assert.True(response2 != null);
        Assert.True(response2.Id == recursoId);
        Assert.True(response2.DataInclusao.Ticks == dataInclusao.Ticks);
        Assert.True(response2.Senha == null);
        Assert.True(response2.Salt == null);
    }
}
Example #14
0
        public static Dictionary <string, string> CreateClientCredentialBodyParameters(
            ICoreLogger logger,
            ICryptographyManager cryptographyManager,
            ClientCredentialWrapper clientCredential,
            string clientId,
            AuthorityEndpoints endpoints,
            bool sendX5C)
        {
            Dictionary <string, string> parameters = new Dictionary <string, string>();

            if (clientCredential != null)
            {
                if (!string.IsNullOrEmpty(clientCredential.Secret))
                {
                    parameters[OAuth2Parameter.ClientSecret] = clientCredential.Secret;
                }
                else
                {
                    if (clientCredential.Assertion == null || clientCredential.ValidTo != 0)
                    {
                        if (!ValidateClientAssertion(clientCredential, endpoints, sendX5C))
                        {
                            logger.Info("Client Assertion does not exist or near expiry.");
                            var jwtToken = new JsonWebToken(cryptographyManager, clientId, endpoints?.SelfSignedJwtAudience);
                            clientCredential.Assertion   = jwtToken.Sign(clientCredential.Certificate, sendX5C);
                            clientCredential.ValidTo     = jwtToken.Payload.ValidTo;
                            clientCredential.ContainsX5C = sendX5C;
                            clientCredential.Audience    = endpoints?.SelfSignedJwtAudience;
                        }
                        else
                        {
                            logger.Info("Reusing the unexpired Client Assertion...");
                        }
                    }

                    parameters[OAuth2Parameter.ClientAssertionType] = OAuth2AssertionType.JwtBearer;
                    parameters[OAuth2Parameter.ClientAssertion]     = clientCredential.Assertion;
                }
            }
            return(parameters);
        }
        public Task AddConfidentialClientParametersAsync(
            OAuth2Client oAuth2Client,
            ICoreLogger logger,
            ICryptographyManager cryptographyManager,
            string clientId,
            string tokenEndpoint,
            bool sendX5C,
            CancellationToken cancellationToken)
        {
            var jwtToken = new JsonWebToken(
                cryptographyManager,
                clientId,
                tokenEndpoint,
                _claimsToSign,
                _appendDefaultClaims);

            string assertion = jwtToken.Sign(Certificate, _base64EncodedThumbprint, sendX5C);

            oAuth2Client.AddBodyParameter(OAuth2Parameter.ClientAssertionType, OAuth2AssertionType.JwtBearer);
            oAuth2Client.AddBodyParameter(OAuth2Parameter.ClientAssertion, assertion);

            return(TaskUtil.CompletedTask);
        }
 public UapTokenCacheBlobStorage(ICryptographyManager cryptographyManager, ICoreLogger logger)
 {
     _cryptographyManager = cryptographyManager;
 }
 public iOSBroker(ICoreLogger logger, ICryptographyManager cryptoManager)
 {
     _logger        = logger;
     _cryptoManager = cryptoManager;
 }
Example #18
0
        public void AddConfidentialClientParameters(
            OAuth2Client oAuth2Client,
            ICoreLogger logger,
            ICryptographyManager cryptographyManager,
            string clientId,
            Authority authority,
            bool sendX5C)
        {
            using (logger.LogMethodDuration())
            {
                switch (AuthenticationType)
                {
                case ConfidentialClientAuthenticationType.ClientCertificate:
                    string tokenEndpoint = authority.GetTokenEndpoint();

                    var jwtToken2 = new JsonWebToken(
                        cryptographyManager,
                        clientId,
                        tokenEndpoint);

                    string assertion2 = jwtToken2.Sign(this, sendX5C);

                    oAuth2Client.AddBodyParameter(OAuth2Parameter.ClientAssertionType, OAuth2AssertionType.JwtBearer);
                    oAuth2Client.AddBodyParameter(OAuth2Parameter.ClientAssertion, assertion2);

                    break;

                case ConfidentialClientAuthenticationType.ClientCertificateWithClaims:
                    tokenEndpoint = authority.GetTokenEndpoint();

                    var jwtToken = new JsonWebToken(
                        cryptographyManager,
                        clientId,
                        tokenEndpoint,
                        ClaimsToSign,
                        AppendDefaultClaims);
                    string assertion = jwtToken.Sign(this, sendX5C);

                    oAuth2Client.AddBodyParameter(OAuth2Parameter.ClientAssertionType, OAuth2AssertionType.JwtBearer);
                    oAuth2Client.AddBodyParameter(OAuth2Parameter.ClientAssertion, assertion);

                    break;

                case ConfidentialClientAuthenticationType.ClientSecret:
                    oAuth2Client.AddBodyParameter(OAuth2Parameter.ClientSecret, Secret);
                    break;

                case ConfidentialClientAuthenticationType.SignedClientAssertion:
                    oAuth2Client.AddBodyParameter(OAuth2Parameter.ClientAssertionType, OAuth2AssertionType.JwtBearer);
                    oAuth2Client.AddBodyParameter(OAuth2Parameter.ClientAssertion, SignedAssertion);
                    break;

                case ConfidentialClientAuthenticationType.SignedClientAssertionDelegate:
                    oAuth2Client.AddBodyParameter(OAuth2Parameter.ClientAssertionType, OAuth2AssertionType.JwtBearer);
                    oAuth2Client.AddBodyParameter(OAuth2Parameter.ClientAssertion, SignedAssertionDelegate.Invoke());
                    break;

                default:
                    throw new NotImplementedException();
                }
            }
        }
 public UapLegacyCachePersistence(ICoreLogger logger, ICryptographyManager cryptographyManager)
 {
     _logger = logger;
     _cryptographyManager = cryptographyManager;
 }
 public FileSystemCredentialPathManager(ICryptographyManager cryptographyManager)
 {
     _cryptographyManager = cryptographyManager;
 }
Example #21
0
        public async Task AddConfidentialClientParametersAsync(OAuth2Client oAuth2Client, ICoreLogger logger, ICryptographyManager cryptographyManager, string clientId, string tokenEndpoint, bool sendX5C, CancellationToken cancellationToken)
        {
            string signedAssertion = await _signedAssertionDelegate(cancellationToken).ConfigureAwait(false);

            oAuth2Client.AddBodyParameter(OAuth2Parameter.ClientAssertionType, OAuth2AssertionType.JwtBearer);
            oAuth2Client.AddBodyParameter(OAuth2Parameter.ClientAssertion, signedAssertion);
        }
 public UapLegacyCachePersistence(ICryptographyManager cryptographyManager)
 {
     _cryptographyManager = cryptographyManager;
 }
Example #23
0
 public DpApiEncryptedFileProvider(ICryptographyManager cryptographyManager, ICoreLogger logger)
 {
     _cryptographyManager = cryptographyManager;
     _logger = logger;
 }
Example #24
0
 public iOSBroker(ICoreLogger logger, ICryptographyManager cryptoManager, CoreUIParent uIParent)
 {
     _logger        = logger;
     _cryptoManager = cryptoManager;
     _uIParent      = uIParent;
 }
 public RecursoAppService(IUnitOfWork unitOfWork, IMapper mapper, ICryptographyManager cryptographyManager)
 {
     _unitOfWork          = unitOfWork;
     _mapper              = mapper;
     _cryptographyManager = cryptographyManager;
 }
Example #26
0
 public RecursoService(IRecursoRepository recursoRepository, IUnitOfWork unitOfWork, ICryptographyManager cryptographyManager)
     : base(recursoRepository, unitOfWork)
 {
     _recursoRepository   = recursoRepository;
     _cryptographyManager = cryptographyManager;
 }
 public RecursoHandler(IUnitOfWork unitOfWork, IMapper mapper, ICryptographyManager cryptographyManager)
 {
     _unitOfWork          = unitOfWork;
     _mapper              = mapper;
     _cryptographyManager = cryptographyManager;
 }
 public JsonWebToken(ICryptographyManager cryptographyManager, string clientId, string audience, IDictionary <string, string> claimsToSign, bool appendDefaultClaims = false)
     : this(cryptographyManager, clientId, audience)
 {
     ClaimsToSign         = claimsToSign;
     _appendDefaultClaims = appendDefaultClaims;
 }
 internal byte[] Sign(ICryptographyManager cryptographyManager, string message)
 {
     return(cryptographyManager.SignWithCertificate(message, Certificate));
 }
Example #30
0
 public RecursoAppService(IMapper mapper, IRepository <Recurso> repository, IUnitOfWork unitOfWork, IRecursoRepository recursoRepository, ICryptographyManager cryptographyManager)
     : base(mapper, repository, unitOfWork)
 {
     _recursoRepository   = recursoRepository;
     _cryptographyManager = cryptographyManager;
 }
Example #31
0
 public Task AddConfidentialClientParametersAsync(OAuth2Client oAuth2Client, ICoreLogger logger, ICryptographyManager cryptographyManager, string clientId, string tokenEndpoint, bool sendX5C, CancellationToken cancellationToken)
 {
     oAuth2Client.AddBodyParameter(OAuth2Parameter.ClientSecret, Secret);
     return(TaskUtil.CompletedTask);
 }