Exemplo n.º 1
0
        public async Task <ActionResult <Api.Track> > GetTrack(string name)
        {
            try
            {
                if (!ModelState.TryValidateRequiredParameter(name, nameof(name)))
                {
                    return(BadRequest(ModelState));
                }
                name = name?.ToLower();

                var mTrack = await tenantRepository.GetTrackByNameAsync(new Track.IdKey {
                    TenantName = RouteBinding.TenantName, TrackName = name
                });

                return(Ok(mapper.Map <Api.Track>(mTrack)));
            }
            catch (CosmosDataException ex)
            {
                if (ex.StatusCode == HttpStatusCode.NotFound)
                {
                    logger.Warning(ex, $"NotFound, Get '{typeof(Api.Track).Name}' by name '{name}'.");
                    return(NotFound(typeof(Api.Track).Name, name));
                }
                throw;
            }
        }
Exemplo n.º 2
0
        protected async Task <ActionResult <List <Api.OAuthClientSecretResponse> > > Get(string partyName)
        {
            try
            {
                if (!ModelState.TryValidateRequiredParameter(partyName, nameof(partyName)))
                {
                    return(BadRequest(ModelState));
                }
                partyName = partyName?.ToLower();

                var oauthDownParty = await tenantRepository.GetAsync <TParty>(await DownParty.IdFormatAsync(RouteBinding, partyName));

                if (oauthDownParty?.Client?.Secrets?.Count > 0)
                {
                    return(Ok(mapper.Map <List <Api.OAuthClientSecretResponse> >(oauthDownParty.Client.Secrets).Set(s => s.ForEach(es => es.Name = new[] { partyName, es.Name }.ToDotList()))));
                }
                else
                {
                    return(Ok(new List <Api.OAuthClientSecretResponse>()));
                }
            }
            catch (CosmosDataException ex)
            {
                if (ex.StatusCode == HttpStatusCode.NotFound)
                {
                    logger.Warning(ex, $"NotFound, Get '{typeof(TParty).Name}' client secrets by name '{partyName}'.");
                    return(NotFound(typeof(TParty).Name, partyName));
                }
                throw;
            }
        }
Exemplo n.º 3
0
        public async Task <ActionResult <Api.LogSettings> > GetTrackLogSetting()
        {
            try
            {
                var mTrack = await tenantRepository.GetTrackByNameAsync(new Track.IdKey {
                    TenantName = RouteBinding.TenantName, TrackName = RouteBinding.TrackName
                });

                if (mTrack.Logging != null && mTrack.Logging.ScopedLogger != null)
                {
                    return(Ok(mapper.Map <Api.LogSettings>(mTrack.Logging.ScopedLogger)));
                }
                else
                {
                    return(NoContent());
                }
            }
            catch (CosmosDataException ex)
            {
                if (ex.StatusCode == HttpStatusCode.NotFound)
                {
                    logger.Warning(ex, $"NotFound, Get {nameof(Track)}.{nameof(Track.Logging)}.{nameof(Track.Logging.ScopedLogger)} by track name '{RouteBinding.TrackName}'.");
                    return(NotFound($"{nameof(Track)}.{nameof(Track.Logging)}.{nameof(Track.Logging.ScopedLogger)}", RouteBinding.TrackName));
                }
                throw;
            }
        }
Exemplo n.º 4
0
        public async Task <bool> ValidateAllowUpPartiesAsync(ModelStateDictionary modelState, string propertyName, DownParty downParty)
        {
            var isValid = true;

            if (downParty.AllowUpParties?.Count() > 0)
            {
                foreach (var upPartyLink in downParty.AllowUpParties)
                {
                    try
                    {
                        var upParty = await tenantService.GetAsync <UpParty>(await UpParty.IdFormat(RouteBinding, upPartyLink.Name));

                        upPartyLink.Type = upParty.Type;
                    }
                    catch (CosmosDataException ex)
                    {
                        if (ex.StatusCode == HttpStatusCode.NotFound)
                        {
                            isValid = false;
                            var errorMessage = $"Allow up party '{upPartyLink.Name}' not found.";
                            logger.Warning(ex, errorMessage);
                            modelState.TryAddModelError(propertyName.ToCamelCase(), errorMessage);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            }
            return(isValid);
        }
        public async Task <ActionResult <List <Api.ClaimMap> > > GetTrackClaimMapping()
        {
            try
            {
                var mTrack = await tenantRepository.GetTrackByNameAsync(new Track.IdKey {
                    TenantName = RouteBinding.TenantName, TrackName = RouteBinding.TrackName
                });

                if (mTrack.ClaimMappings?.Count > 0)
                {
                    return(Ok(mapper.Map <List <Api.ClaimMap> >(mTrack.ClaimMappings)));
                }
                else
                {
                    return(NoContent());
                }
            }
            catch (CosmosDataException ex)
            {
                if (ex.StatusCode == HttpStatusCode.NotFound)
                {
                    logger.Warning(ex, $"NotFound, Get {nameof(Track)}.{nameof(Track.ClaimMappings)} by track name '{RouteBinding.TrackName}'.");
                    return(NotFound($"{nameof(Track)}.{nameof(Track.ClaimMappings)}", RouteBinding.TrackName));
                }
                throw;
            }
        }
Exemplo n.º 6
0
 public virtual NotFoundObjectResult NotFound(string typeName, string name)
 {
     try
     {
         throw new Exception($"{typeName} '{name}' not found.");
     }
     catch (Exception ex)
     {
         logger.Warning(ex);
         return(base.NotFound(ex.Message));
     }
 }
Exemplo n.º 7
0
        public async Task SendEmailAsync(MailAddress toEmail, string subject, string body)
        {
            if (toEmail == null)
            {
                throw new ArgumentNullException(nameof(toEmail));
            }

            try
            {
                var emailSettings = GetSettings();

                if (!emailSettings.SendgridApiKey.IsNullOrWhiteSpace())
                {
                    logger.ScopeTrace(() => $"Send email with Sendgrid using {(RouteBinding.SendEmail == null ? "default" : "track")} settings .");
                    await SendEmailWithSendgridAsync(emailSettings, toEmail, subject, body);
                }
                else if (!emailSettings.SmtpHost.IsNullOrWhiteSpace())
                {
                    logger.ScopeTrace(() => $"Send email with SMTP using {(RouteBinding.SendEmail == null ? "default" : "track")} settings .");
                    await SendEmailWithSmtpAsync(emailSettings, toEmail, subject, body);
                }
                else
                {
                    //TODO add support for other email providers
                    throw new NotImplementedException("Email provider not supported.");
                }
            }
            catch (EmailConfigurationException cex)
            {
                logger.Warning(cex);
                return;
            }
        }
Exemplo n.º 8
0
        public async Task <bool> PopulateModelAsync(ModelStateDictionary modelState, OidcUpParty mp)
        {
            var isValid = true;

            try
            {
                if (mp.UpdateState != PartyUpdateStates.Manual)
                {
                    await oidcDiscoveryReadLogic.PopulateModelAsync(mp);

                    if (mp.UpdateState == PartyUpdateStates.AutomaticStopped)
                    {
                        mp.UpdateState = PartyUpdateStates.Automatic;
                    }

                    if (mp.EditIssuersInAutomatic == false)
                    {
                        mp.EditIssuersInAutomatic = null;
                    }
                }
                else
                {
                    mp.EditIssuersInAutomatic = null;
                }
            }
            catch (Exception ex)
            {
                isValid = false;
                logger.Warning(ex);
                modelState.TryAddModelError(nameof(mp.Authority).ToCamelCase(), ex.GetAllMessagesJoined());
            }
            return(isValid);
        }
Exemplo n.º 9
0
        public async Task <ActionResult <HashSet <Api.Track> > > GetFilterTrack(string filterName)
        {
            try
            {
                var idKey = new Track.IdKey {
                    TenantName = RouteBinding.TenantName, TrackName = RouteBinding.TrackName
                };
                var mTracks = filterName.IsNullOrWhiteSpace() ? await tenantRepository.GetListAsync <Track>(idKey, whereQuery : p => p.DataType.Equals(dataType)) : await tenantRepository.GetListAsync <Track>(idKey, whereQuery : p => p.DataType.Equals(dataType) && p.Name.Contains(filterName));

                var aTracks = new HashSet <Api.Track>(mTracks.Count());
                foreach (var mTrack in mTracks.OrderBy(t => t.Name))
                {
                    aTracks.Add(mapper.Map <Api.Track>(mTrack));
                }
                return(Ok(aTracks));
            }
            catch (CosmosDataException ex)
            {
                if (ex.StatusCode == HttpStatusCode.NotFound)
                {
                    logger.Warning(ex, $"NotFound, Get '{typeof(Api.Track).Name}' by filter name '{filterName}'.");
                    return(NotFound(typeof(Api.Track).Name, filterName));
                }
                throw;
            }
        }
Exemplo n.º 10
0
        public async Task <ActionResult <HashSet <Api.User> > > GetFilterUser(string filterEmail)
        {
            try
            {
                var idKey = new Track.IdKey {
                    TenantName = RouteBinding.TenantName, TrackName = RouteBinding.TrackName,
                };
                var mUsers = filterEmail.IsNullOrWhiteSpace() ? await tenantRepository.GetListAsync <User>(idKey, whereQuery : u => u.DataType.Equals(dataType)) : await tenantRepository.GetListAsync <User>(idKey, whereQuery : u => u.DataType.Equals(dataType) && u.Email.Contains(filterEmail));

                var aUsers = new HashSet <Api.User>(mUsers.Count());
                foreach (var mUser in mUsers.OrderBy(t => t.Email))
                {
                    aUsers.Add(mapper.Map <Api.User>(mUser));
                }
                return(Ok(aUsers));
            }
            catch (CosmosDataException ex)
            {
                if (ex.StatusCode == HttpStatusCode.NotFound)
                {
                    logger.Warning(ex, $"NotFound, Get '{typeof(Api.User).Name}' by filter email '{filterEmail}'.");
                    return(NotFound(typeof(Api.User).Name, filterEmail));
                }
                throw;
            }
        }
Exemplo n.º 11
0
        public async Task <ActionResult <HashSet <Api.DownParty> > > GetFilterDownParty(string filterName)
        {
            try
            {
                var doFilterPartyType = Enum.TryParse <PartyTypes>(filterName, out var filterPartyType);
                var idKey             = new Track.IdKey {
                    TenantName = RouteBinding.TenantName, TrackName = RouteBinding.TrackName
                };
                var mDownPartys = filterName.IsNullOrWhiteSpace() ? await tenantRepository.GetListAsync <DownParty>(idKey, whereQuery : p => p.DataType.Equals(dataType)) : await tenantRepository.GetListAsync <DownParty>(idKey, whereQuery : p => p.DataType.Equals(dataType) && (p.Name.Contains(filterName) || (doFilterPartyType && p.Type == filterPartyType)));

                var aDownPartys = new HashSet <Api.DownParty>(mDownPartys.Count());
                foreach (var mDownParty in mDownPartys.OrderBy(p => p.Name))
                {
                    aDownPartys.Add(mapper.Map <Api.DownParty>(mDownParty));
                }
                return(Ok(aDownPartys));
            }
            catch (CosmosDataException ex)
            {
                if (ex.StatusCode == HttpStatusCode.NotFound)
                {
                    logger.Warning(ex, $"NotFound, Get '{typeof(Api.DownParty).Name}' by filter name '{filterName}'.");
                    return(NotFound(typeof(Api.DownParty).Name, filterName));
                }
                throw;
            }
        }
Exemplo n.º 12
0
        public async Task <IActionResult> EndSessionRequestAsync(string partyId)
        {
            logger.ScopeTrace("Up, OIDC End session request.");
            var oidcUpSequenceData = await sequenceLogic.GetSequenceDataAsync <OidcUpSequenceData>(remove : false);

            if (!oidcUpSequenceData.UpPartyId.Equals(partyId, StringComparison.Ordinal))
            {
                throw new Exception("Invalid up-party id.");
            }
            logger.SetScopeProperty("upPartyId", oidcUpSequenceData.UpPartyId);

            var party = await tenantRepository.GetAsync <OidcUpParty>(oidcUpSequenceData.UpPartyId);

            logger.SetScopeProperty("upPartyClientId", party.Client.ClientId);
            ValidatePartyLogoutSupport(party);

            var postLogoutRedirectUrl    = HttpContext.GetUpPartyUrl(party.Name, Constants.Routes.OAuthController, Constants.Endpoints.EndSessionResponse, partyBindingPattern: party.PartyBindingPattern);
            var rpInitiatedLogoutRequest = new RpInitiatedLogoutRequest
            {
                PostLogoutRedirectUri = postLogoutRedirectUrl,
                State = SequenceString
            };

            var session = await sessionUpPartyLogic.GetSessionAsync(party);

            if (session != null)
            {
                try
                {
                    if (!oidcUpSequenceData.SessionId.Equals(session.SessionId, StringComparison.Ordinal))
                    {
                        throw new Exception("Requested session ID do not match up-party session ID.");
                    }
                }
                catch (Exception ex)
                {
                    logger.Warning(ex);
                }

                rpInitiatedLogoutRequest.IdTokenHint = session.IdToken;

                oidcUpSequenceData.SessionDownPartyLinks = session.DownPartyLinks;
                oidcUpSequenceData.SessionClaims         = session.Claims;
                await sequenceLogic.SaveSequenceDataAsync(oidcUpSequenceData);
            }
            logger.ScopeTrace($"Up, End session request '{rpInitiatedLogoutRequest.ToJsonIndented()}'.");

            _ = await sessionUpPartyLogic.DeleteSessionAsync(session);

            await oauthRefreshTokenGrantLogic.DeleteRefreshTokenGrantsAsync(oidcUpSequenceData.SessionId);

            securityHeaderLogic.AddFormActionAllowAll();

            var nameValueCollection = rpInitiatedLogoutRequest.ToDictionary();

            logger.ScopeTrace($"Up, End session request URL '{party.Client.EndSessionUrl}'.");
            logger.ScopeTrace("Up, Sending OIDC End session request.", triggerEvent: true);
            return(await nameValueCollection.ToRedirectResultAsync(party.Client.EndSessionUrl));
        }
Exemplo n.º 13
0
        public async Task <ActionResult <Api.TrackKeyItemsContained> > GetTrackKeyContained()
        {
            try
            {
                var mTrack = await tenantRepository.GetTrackByNameAsync(new Track.IdKey {
                    TenantName = RouteBinding.TenantName, TrackName = RouteBinding.TrackName
                });

                try
                {
                    if (mTrack.Key.Type != TrackKeyType.Contained)
                    {
                        throw new ValidationException($"Only {Api.TrackKeyType.Contained} keys is supported.");
                    }
                }
                catch (ValidationException vex)
                {
                    logger.Warning(vex);
                    ModelState.TryAddModelError(string.Empty, vex.Message);
                    return(BadRequest(ModelState));
                }

                return(Ok(mapper.Map <Api.TrackKeyItemsContained>(mTrack.Key)));
            }
            catch (CosmosDataException ex)
            {
                if (ex.StatusCode == HttpStatusCode.NotFound)
                {
                    logger.Warning(ex, $"NotFound, Get '{typeof(Api.TrackKeyItemsContained).Name}' contained by track name '{RouteBinding.TrackName}'.");
                    return(NotFound(typeof(Api.TrackKeyItemsContained).Name, RouteBinding.TrackName));
                }
                throw;
            }
        }
Exemplo n.º 14
0
        public async Task <ActionResult <Api.Tenant> > GetMyTenant()
        {
            try
            {
                var MTenant = await tenantRepository.GetTenantByNameAsync(RouteBinding.TenantName);

                return(Ok(mapper.Map <Api.Tenant>(MTenant)));
            }
            catch (CosmosDataException ex)
            {
                if (ex.StatusCode == HttpStatusCode.NotFound)
                {
                    logger.Warning(ex, $"NotFound, Get my '{typeof(Api.Tenant).Name}'.");
                    return(NotFound(typeof(Api.Tenant).Name, RouteBinding.TenantName));
                }
                throw;
            }
        }
Exemplo n.º 15
0
        public async Task <ActionResult <Api.TrackKey> > GetTrackKeyType()
        {
            try
            {
                var mTrack = await tenantRepository.GetTrackByNameAsync(new Track.IdKey {
                    TenantName = RouteBinding.TenantName, TrackName = RouteBinding.TrackName
                });

                return(Ok(mapper.Map <Api.TrackKey>(mTrack.Key)));
            }
            catch (CosmosDataException ex)
            {
                if (ex.StatusCode == HttpStatusCode.NotFound)
                {
                    logger.Warning(ex, $"NotFound, Get '{typeof(Api.TrackKey).Name}' type by track name '{RouteBinding.TrackName}'.");
                    return(NotFound(typeof(Api.TrackKey).Name, RouteBinding.TrackName));
                }
                throw;
            }
        }
Exemplo n.º 16
0
        public async Task <ActionResult <Api.ResourceItem> > GetTrackResource(int resourceId)
        {
            try
            {
                var mTrack = await tenantRepository.GetTrackByNameAsync(new Track.IdKey {
                    TenantName = RouteBinding.TenantName, TrackName = RouteBinding.TrackName
                });

                var resourceItem = mTrack.Resources?.SingleOrDefault(r => r.Id == resourceId);
                return(Ok(mapper.Map <Api.ResourceItem>(resourceItem)));
            }
            catch (CosmosDataException ex)
            {
                if (ex.StatusCode == HttpStatusCode.NotFound)
                {
                    logger.Warning(ex, $"NotFound, Get Track.Resource by track name '{RouteBinding.TrackName}' and resource id '{resourceId}'.");
                    return(NotFound("Track.Resource", Convert.ToString(resourceId)));
                }
                throw;
            }
        }
Exemplo n.º 17
0
        public async Task <IActionResult> LogoutRequestAsync(IEnumerable <string> partyIds, SingleLogoutSequenceData sequenceData)
        {
            var frontChannelLogoutRequest = new FrontChannelLogoutRequest
            {
                Issuer    = trackIssuerLogic.GetIssuer(),
                SessionId = sequenceData.Claims.FindFirstValue(c => c.Claim == JwtClaimTypes.SessionId)
            };
            var nameValueCollection = frontChannelLogoutRequest.ToDictionary();

            TParty firstParty      = null;
            var    partyLogoutUrls = new List <string>();

            foreach (var partyId in partyIds)
            {
                try
                {
                    var party = await tenantRepository.GetAsync <TParty>(partyId);

                    if (party.Client == null)
                    {
                        throw new NotSupportedException("Party Client not configured.");
                    }
                    if (party.Client.FrontChannelLogoutUri.IsNullOrWhiteSpace())
                    {
                        throw new Exception("Front channel logout URI not configured.");
                    }

                    firstParty = party;
                    if (party.Client.FrontChannelLogoutSessionRequired)
                    {
                        partyLogoutUrls.Add(QueryHelpers.AddQueryString(party.Client.FrontChannelLogoutUri, nameValueCollection));
                    }
                    else
                    {
                        partyLogoutUrls.Add(party.Client.FrontChannelLogoutUri);
                    }
                }
                catch (Exception ex)
                {
                    logger.Warning(ex, $"Unable to get front channel logout for party ID '{partyId}'.");
                }
            }

            if (partyLogoutUrls.Count() <= 0 || firstParty == null)
            {
                throw new InvalidOperationException("Unable to complete front channel logout. Please close the browser to logout.");
            }

            securityHeaderLogic.AddFrameSrc(partyLogoutUrls);
            var redirectUrl = HttpContext.GetDownPartyUrl(firstParty.Name, sequenceData.UpPartyName, Constants.Routes.OAuthController, Constants.Endpoints.FrontChannelLogoutDone, includeSequence: true);

            return(partyLogoutUrls.ToHtmIframePage(redirectUrl, "FoxIDs").ToContentResult());
        }
Exemplo n.º 18
0
 private bool ValidateSigningKeys(ModelStateDictionary modelState, string propertyName, List<JsonWebKey> keys)
 {
     var isValid = true;
     try
     {
         if (keys != null)
         {
             var anyDuplicate = keys.GroupBy(x => x.X5t).Any(g => g.Count() > 1);
             if (anyDuplicate)
             {
                 throw new ValidationException("Signature validation keys (certificates) has duplicates.");
             }
         }
     }
     catch (ValidationException ex)
     {
         isValid = false;
         logger.Warning(ex);
         modelState.TryAddModelError(propertyName.ToCamelCase(), ex.Message);
     }
     return isValid;
 }
Exemplo n.º 19
0
        protected async Task <ActionResult <Api.OAuthClientSecretResponse> > Get(string partyName)
        {
            try
            {
                if (!ModelState.TryValidateRequiredParameter(partyName, nameof(partyName)))
                {
                    return(BadRequest(ModelState));
                }

                var oauthDownParty = await tenantService.GetAsync <TParty>(await DownParty.IdFormat(RouteBinding, partyName));

                return(Ok(mapper.Map <List <Api.OAuthClientSecretResponse> >(oauthDownParty.Client.Secrets).Select(c => { c.Name = new[] { partyName, c.Name }.ToDotList(); return c; })));
            }
            catch (CosmosDataException ex)
            {
                if (ex.StatusCode == HttpStatusCode.NotFound)
                {
                    logger.Warning(ex, $"Get '{typeof(TParty).Name}' client secrets by name '{partyName}'.");
                    return(NotFound(typeof(TParty).Name, partyName));
                }
                throw;
            }
        }
Exemplo n.º 20
0
        public async Task <ActionResult <Api.User> > GetUser(string email)
        {
            try
            {
                if (!ModelState.TryValidateRequiredParameter(email, nameof(email)))
                {
                    return(BadRequest(ModelState));
                }

                var mUser = await tenantRepository.GetAsync <Models.User>(await Models.User.IdFormat(RouteBinding, email?.ToLower()));

                return(Ok(mapper.Map <Api.User>(mUser)));
            }
            catch (CosmosDataException ex)
            {
                if (ex.StatusCode == HttpStatusCode.NotFound)
                {
                    logger.Warning(ex, $"NotFound, Get '{typeof(Api.User).Name}' by email '{email}'.");
                    return(NotFound(typeof(Api.User).Name, email));
                }
                throw;
            }
        }
Exemplo n.º 21
0
        protected async Task <ActionResult <AParty> > Get(string name)
        {
            try
            {
                if (!ModelState.TryValidateRequiredParameter(name, nameof(name)))
                {
                    return(BadRequest(ModelState));
                }

                var MParty = await tenantService.GetAsync <MParty>(await GetId(name));

                return(Ok(mapper.Map <AParty>(MParty)));
            }
            catch (CosmosDataException ex)
            {
                if (ex.StatusCode == HttpStatusCode.NotFound)
                {
                    logger.Warning(ex, $"Get '{typeof(AParty).Name}' by name '{name}'.");
                    return(NotFound(typeof(AParty).Name, name));
                }
                throw;
            }
        }
Exemplo n.º 22
0
        public bool ValidateApiModelClaimTransforms <T>(ModelStateDictionary modelState, List <T> claimTransforms) where T : Api.ClaimTransform
        {
            var isValid = true;

            try
            {
                if (claimTransforms?.Count() > 0)
                {
                    var duplicatedOrderNumber = claimTransforms.GroupBy(ct => ct.Order as int?).Where(g => g.Count() > 1).Select(g => g.Key).FirstOrDefault();
                    if (duplicatedOrderNumber >= 0)
                    {
                        throw new ValidationException($"Duplicated claim transform order number '{duplicatedOrderNumber}'");
                    }
                }
            }
            catch (ValidationException vex)
            {
                isValid = false;
                logger.Warning(vex);
                modelState.TryAddModelError(nameof(Api.OAuthDownParty.ClaimTransforms).ToCamelCase(), vex.Message);
            }
            return(isValid);
        }
Exemplo n.º 23
0
        private TMessage Get(bool delete)
        {
            if (RouteBinding.TenantName.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(RouteBinding.TenantName), RouteBinding.GetTypeName());
            }
            if (RouteBinding.TrackName.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(RouteBinding.TrackName), RouteBinding.GetTypeName());
            }
            if (RouteBinding.UpParty == null)
            {
                throw new ArgumentNullException(nameof(RouteBinding.UpParty), RouteBinding.GetTypeName());
            }

            logger.ScopeTrace($"Get Cookie '{typeof(TMessage).Name}', Route '{RouteBinding.Route}', Delete '{delete}'.");

            var cookie = httpContextAccessor.HttpContext.Request.Cookies[CookieName()];

            if (!cookie.IsNullOrWhiteSpace())
            {
                try
                {
                    var envelope = CookieEnvelope <TMessage> .FromCookieString(CreateProtector(), cookie);

                    if (delete)
                    {
                        logger.ScopeTrace($"Delete Cookie, '{typeof(TMessage).Name}', Route '{RouteBinding.Route}'.");
                        DeleteByName(CookieName());
                    }

                    return(envelope.Message);
                }
                catch (CryptographicException ex)
                {
                    logger.Warning(ex, $"Unable to Unprotect Cookie '{typeof(TMessage).Name}', deleting cookie.");
                    DeleteByName(CookieName());
                    return(null);
                }
                catch (Exception ex)
                {
                    throw new Exception($"Unable to Read Cookie '{typeof(TMessage).Name}'.", ex);
                }
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 24
0
        public async Task <ActionResult <Api.SendEmail> > GetTrackSendEmail()
        {
            try
            {
                var mTrack = await tenantRepository.GetTrackByNameAsync(new Track.IdKey {
                    TenantName = RouteBinding.TenantName, TrackName = RouteBinding.TrackName
                });

                if (mTrack.SendEmail == null)
                {
                    return(NoContent());
                }
                return(Ok(mapper.Map <Api.SendEmail>(mTrack.SendEmail)));
            }
            catch (CosmosDataException ex)
            {
                if (ex.StatusCode == HttpStatusCode.NotFound)
                {
                    logger.Warning(ex, $"NotFound, Get Track.SendEmail by track name '{RouteBinding.TrackName}'.");
                    return(NotFound("Track.SendEmail", RouteBinding.TrackName));
                }
                throw;
            }
        }
Exemplo n.º 25
0
        public async Task <bool> PopulateModelAsync(ModelStateDictionary modelState, OidcUpParty mp)
        {
            var isValid = true;

            try
            {
                if (mp.UpdateState != PartyUpdateStates.Manual)
                {
                    (var oidcDiscovery, var jsonWebKeySet) = await oidcDiscoveryReadLogic.GetOidcDiscoveryAndValidateAsync(mp.Authority);

                    mp.LastUpdated = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
                    if (mp.EditIssuersInAutomatic != true || string.IsNullOrWhiteSpace(mp.Issuers?.FirstOrDefault()))
                    {
                        mp.Issuers = new List <string> {
                            oidcDiscovery.Issuer
                        };
                    }
                    mp.Client.AuthorizeUrl = oidcDiscovery.AuthorizationEndpoint;
                    mp.Client.TokenUrl     = oidcDiscovery.TokenEndpoint;
                    if (!oidcDiscovery.EndSessionEndpoint.IsNullOrEmpty())
                    {
                        mp.Client.EndSessionUrl = oidcDiscovery.EndSessionEndpoint;
                    }
                    mp.Keys = jsonWebKeySet.Keys?.ToList();

                    if (mp.UpdateState == PartyUpdateStates.AutomaticStopped)
                    {
                        mp.UpdateState = PartyUpdateStates.Automatic;
                    }

                    if (mp.EditIssuersInAutomatic == false)
                    {
                        mp.EditIssuersInAutomatic = null;
                    }
                }
                else
                {
                    mp.EditIssuersInAutomatic = null;
                }
            }
            catch (Exception ex)
            {
                isValid = false;
                logger.Warning(ex);
                modelState.TryAddModelError(nameof(mp.Authority).ToCamelCase(), ex.GetAllMessagesJoined());
            }
            return(isValid);
        }
Exemplo n.º 26
0
        private bool ValidateSignatureAlgorithm(ModelStateDictionary modelState, string propertyName, string signatureAlgorithm)
        {
            var isValid = true;

            try
            {
                SignatureAlgorithm.ValidateAlgorithm(signatureAlgorithm);
            }
            catch (NotSupportedException nsex)
            {
                isValid = false;
                var errorMessage = $"Signature algorithm '{signatureAlgorithm}' not supported.";
                logger.Warning(nsex, errorMessage);
                modelState.TryAddModelError(propertyName.ToCamelCase(), $"{errorMessage}{nsex.Message}");
            }
            return(isValid);
        }
Exemplo n.º 27
0
 public ActionResult <List <Api.ResourceName> > GetFilterResourceName(string filterName)
 {
     try
     {
         var resourceEnvelope    = embeddedResourceLogic.GetResourceEnvelope();
         var filderResourceNames = filterName.IsNullOrWhiteSpace() ? resourceEnvelope.Names : resourceEnvelope.Names.Where(r => r.Name.Contains(filterName, System.StringComparison.OrdinalIgnoreCase));
         return(Ok(mapper.Map <List <Api.ResourceName> >(filderResourceNames.OrderBy(r => r.Name))));
     }
     catch (CosmosDataException ex)
     {
         if (ex.StatusCode == HttpStatusCode.NotFound)
         {
             logger.Warning(ex, $"NotFound, Get '{typeof(ResourceEnvelope).Name}'.");
             return(NotFound(typeof(ResourceEnvelope).Name, "master"));
         }
         throw;
     }
 }
Exemplo n.º 28
0
        private async Task <List <UpPartyLink> > GetAllowedToUpPartyIds(TelemetryScopedLogger scopedLogger, Track.IdKey trackIdKey, Group toUpPartyGroup, DownParty downParty)
        {
            var toUpParties = new List <UpPartyLink>();

            if (toUpPartyGroup.Captures.Count > 5)
            {
                throw new ArgumentException($"More then 5 to up-party for down-party '{downParty.Id}'.");
            }

            foreach (Capture upPartyCapture in toUpPartyGroup.Captures)
            {
                var toUpPartyIdKey = new Party.IdKey
                {
                    TenantName = trackIdKey.TenantName,
                    TrackName  = trackIdKey.TrackName,
                    PartyName  = upPartyCapture.Value,
                };
                await toUpPartyIdKey.ValidateObjectAsync();

                var allowUpParty = downParty.AllowUpParties.Where(ap => ap.Name == toUpPartyIdKey.PartyName).SingleOrDefault();
                if (allowUpParty != null)
                {
                    toUpParties.Add(allowUpParty);
                }
                else
                {
                    try
                    {
                        throw new ArgumentException($"Up-party name '{toUpPartyIdKey.PartyName}' not allowed for down-party '{downParty.Id}',");
                    }
                    catch (Exception ex)
                    {
                        scopedLogger.Warning(ex);
                    }
                }
            }

            if (toUpParties.Count() > 1)
            {
                throw new NotSupportedException("Currently only 0 and 1 to up-party is supported.");
            }
            return(toUpParties);
        }
Exemplo n.º 29
0
            public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
            {
                var routeBinding = context.HttpContext.GetRouteBinding();

                try
                {
                    if (!routeBinding.TenantName.Equals(Constants.Routes.MasterTenantName, StringComparison.OrdinalIgnoreCase))
                    {
                        throw new UnauthorizedAccessException("API require master tenant.");
                    }

                    await next();
                }
                catch (UnauthorizedAccessException uaex)
                {
                    logger.Warning(uaex);
                    context.Result = new UnauthorizedResult();
                }
            }
Exemplo n.º 30
0
        private TMessage Get(bool delete, bool tryGet = false)
        {
            if (tryGet && RouteBindingDoNotExists())
            {
                return(null);
            }
            CheckRouteBinding();

            logger.ScopeTrace($"Get Cookie '{typeof(TMessage).Name}', Route '{RouteBinding.Route}', Delete '{delete}'.");

            var cookie = httpContextAccessor.HttpContext.Request.Cookies[CookieName()];

            if (!cookie.IsNullOrWhiteSpace())
            {
                try
                {
                    var envelope = CookieEnvelope <TMessage> .FromCookieString(CreateProtector(), cookie);

                    if (delete)
                    {
                        logger.ScopeTrace($"Delete Cookie, '{typeof(TMessage).Name}', Route '{RouteBinding.Route}'.");
                        DeleteByName(CookieName());
                    }

                    return(envelope.Message);
                }
                catch (CryptographicException ex)
                {
                    logger.Warning(ex, $"Unable to Unprotect Cookie '{typeof(TMessage).Name}', deleting cookie.");
                    DeleteByName(CookieName());
                    return(null);
                }
                catch (Exception ex)
                {
                    throw new Exception($"Unable to Read Cookie '{typeof(TMessage).Name}'.", ex);
                }
            }
            else
            {
                return(null);
            }
        }