public SearchByClientRequestInterpreter(
     IScopedStorage <HttpContext> httpContextStorage,
     IJsonPropertyNameResolver jsonPropertyNameResolver)
 {
     this.httpContextStorage     = httpContextStorage;
     this.SearchQueryArgumentKey = jsonPropertyNameResolver.Resolve("Q");
 }
Esempio n. 2
0
 public TokenExchangeGrantValidator(
     IScopedContext <TenantRequestContext> scopedTenantRequestContext,
     IScopedStorage scopedStorage,
     IResourceStore resourceStore,
     IScopedOptionalClaims scopedOptionalClaims,
     IConsentExternalService consentExternalService,
     IExternalServicesStore externalServicesStore,
     IScopedOverrideRawScopeValues scopedOverrideRawScopeValues,
     ISerializer serializer,
     IConsentDiscoveryCacheAccessor consentDiscoveryCacheAccessor,
     IOptions <TokenExchangeOptions> tokenExchangeOptions,
     IIdentityTokenValidator identityTokenValidator,
     ITokenValidator tokenValidator,
     ILogger <TokenExchangeGrantValidator> logger)
 {
     _scopedTenantRequestContext = scopedTenantRequestContext;
     _scopedStorage                 = scopedStorage;
     _serializer                    = serializer;
     _resourceStore                 = resourceStore;
     _scopedOptionalClaims          = scopedOptionalClaims;
     _consentExternalService        = consentExternalService;
     _externalServicesStore         = externalServicesStore;
     _scopedOverrideRawScopeValues  = scopedOverrideRawScopeValues;
     _consentDiscoveryCacheAccessor = consentDiscoveryCacheAccessor;
     _tokenExchangeOptions          = tokenExchangeOptions.Value;
     _identityTokenValidator        = identityTokenValidator;
     _tokenValidator                = tokenValidator;
     _logger = logger;
 }
Esempio n. 3
0
 public RestCollectionLinkGenerator(
     IScopedStorage <HttpContext> httpContextStorage,
     IQueryArgumentKeys queryArgumentKeys)
 {
     this.request           = httpContextStorage.Value.Request;
     this.queryArgumentKeys = queryArgumentKeys;
 }
Esempio n. 4
0
 public FilterByClientRequestInterpreter(
     IScopedStorage <HttpContext> httpContextStorage,
     IJsonPropertyNameResolver jsonPropertyNameResolver)
 {
     this.jsonPropertyNameResolver = jsonPropertyNameResolver;
     this.queryCollection          = httpContextStorage.Value.Request.Query;
 }
Esempio n. 5
0
        public async Task Invoke(HttpContext httpContext, IScopedStorage scopedStorage)
        {
            var handled = (bool)scopedStorage.Storage["IdentityServer:Handled"];

            if (handled)
            {
                // this is where we get a chance to write those response headers on what we believe is the way out.
                // as we classify that when the IdentityServer middleware finishes it on the way out.
                var requestRecord = (IdentityServerRequestRecord)scopedStorage.Storage["IdentityServerRequestRecord"];
                var result        = (IEndpointResult)scopedStorage.Storage["IEndpointResult"];
                var tokenResult   = result as ITokenEndpointResult;
                var error         = tokenResult == null;

                foreach (var evaluator in _evaluators)
                {
                    var directive = await ProcessPostEvaluatorAsync(evaluator, requestRecord, error);

                    if (directive == RequestTrackerEvaluatorDirective.DenyRequest)
                    {
                        return; // do not continue to the real IdentityServer4 middleware.
                    }
                }

                await result.ExecuteAsync(httpContext);

                return;
            }
            await _next(httpContext);
        }
Esempio n. 6
0
 public PaginationByClientRequestInterpreter(
     IScopedStorage <HttpContext> httpContextStorage,
     IQueryArgumentKeys queryArgumentKeys)
 {
     this.queryCollection   = httpContextStorage.Value.Request.Query;
     this.queryArgumentKeys = queryArgumentKeys;
 }
 public SearchByClientRequestPipeFactory(
     IScopedStorage <HttpContext> httpContextStorage,
     IQueryArgumentKeys queryArgumentKeys)
 {
     this.httpContextStorage = httpContextStorage;
     this.queryArgumentKeys  = queryArgumentKeys;
 }
Esempio n. 8
0
 public OrderByClientRequestInterpreter(
     IScopedStorage <HttpContext> httpContextStorage,
     IJsonPropertyNameResolver jsonPropertyNameResolver)
 {
     this.jsonPropertyNameResolver = jsonPropertyNameResolver;
     this.queryCollection          = httpContextStorage.Value.Request.Query;
     this.OrderByQueryArgumentKey  = this.jsonPropertyNameResolver.Resolve("Sort");
 }
        public async Task Invoke(HttpContext httpContext, IScopedStorage scopedStorage)
        {
            if (!string.IsNullOrEmpty(PathRootUrl))
            {
                FixUpPath(httpContext);
            }

            // start tracking
            await FetchDiscoveryData(httpContext);

            var endpointKey = (from item in _endpointDictionary
                               where item.Value == httpContext.Request.Path.Value
                               select item.Key).FirstOrDefault();

            if (endpointKey == null)
            {
                // not for us
                await _next(httpContext);

                return;
            }

            _logger.LogInformation($"endpointKey={endpointKey},path={httpContext.Request.Path}");
            var requestRecord = new IdentityServerRequestRecord
            {
                HttpContext = httpContext,
                EndpointKey = endpointKey
            };

            // validate HTTP for clients
            if (HttpMethods.IsPost(httpContext.Request.Method) && httpContext.Request.HasFormContentType)
            {
                // validate client
                var clientResult = await _clientValidator.ValidateAsync(httpContext);

                if (!clientResult.IsError)
                {
                    requestRecord.Client = clientResult.Client;
                }
            }

            foreach (var evaluator in _evaluators)
            {
                var directive = await ProcessPreEvaluatorAsync(evaluator, requestRecord);

                if (directive == RequestTrackerEvaluatorDirective.DenyRequest)
                {
                    return; // do not continue to the real IdentityServer4 middleware.
                }
            }

            scopedStorage.Storage["IdentityServerRequestRecord"] = requestRecord;
            //
            // The following invoke is letting the request continue on into the pipeline
            //

            await _next(httpContext);
        }
 public EntityInsertionPipe(
     DbContext context,
     IScopedStorage <TInput> storage,
     IOutputPipe <TInput> parent)
     : base(parent)
 {
     this.context = context;
     this.storage = storage;
 }
 public PaginationByClientRequestInterpreter(
     IScopedStorage <HttpContext> httpContextStorage,
     IJsonPropertyNameResolver jsonPropertyNameResolver)
 {
     this.queryCollection        = httpContextStorage.Value.Request.Query;
     this.requestHeader          = httpContextStorage.Value.Request.Headers;
     this.LimitQueryArgumentKey  = jsonPropertyNameResolver.Resolve("Limit");
     this.OffsetQueryArgumentKey = jsonPropertyNameResolver.Resolve("Offset");
 }
 public CollectionMappingPipeFactory(
     IRestCollectionLinkGenerator linkGenerator,
     IScopedStorage <PaginationMetaInfo> paginationMetaInfoStorage,
     IQueryableTransformer <TInput> queryableTransformer)
 {
     this.linkGenerator             = linkGenerator;
     this.paginationMetaInfoStorage = paginationMetaInfoStorage;
     this.queryableTransformer      = queryableTransformer;
 }
 public PaginationByClientRequestPipeFactory(
     IPaginationByClientRequestInterpreter interpreter,
     IScopedStorage <PaginationMetaInfo> paginationMetaInfoStorage,
     IQueryableTransformer <TInput> queryableTransformer)
 {
     this.interpreter = interpreter;
     this.paginationMetaInfoStorage = paginationMetaInfoStorage;
     this.queryableTransformer      = queryableTransformer;
 }
Esempio n. 14
0
 public WithDbContextObserver(
     Action <TSource, DbContext> action,
     IScopedStorage <DbContext> context,
     IObserver <TSource> child,
     IDisposable disposable)
     : base(child, disposable)
 {
     this.action  = action;
     this.context = context;
 }
Esempio n. 15
0
 public MapToQueryableObserver(
     Func <TSource, DbContext, IQueryable <TTarget> > mapping,
     IScopedStorage <DbContext> context,
     IObserver <IQueryable <TTarget> > child,
     IDisposable disposable)
     : base(child, disposable)
 {
     this.mapping = mapping;
     this.context = context;
 }
 public SearchByClientRequestPipe(
     IScopedStorage <HttpContext> httpContextStorage,
     IQueryArgumentKeys queryArgumentKeys,
     Func <string, Expression <Func <TInput, bool> > > search,
     IOutputPipe <IQueryable <TInput> > parent)
     : base(parent)
 {
     this.queryArgumentKeys = queryArgumentKeys;
     this.search            = search;
     this.queryCollection   = httpContextStorage.Value.Request.Query;
 }
        public static T Get <T>(this IScopedStorage scopedStorage, string key) where T : class
        {
            object obj;

            if (scopedStorage.TryGetValue(key, out obj))
            {
                return(obj as T);
            }

            return(null);
        }
 public OptionsResultPipe(
     Func <TInput, IEnumerable <HttpVerb> > verbGeneration,
     IHttpVerbMap httpVerbMap,
     IScopedStorage <HttpContext> httpContextStorage,
     IOutputPipe <TInput> parent)
     : base(parent)
 {
     this.verbGeneration     = verbGeneration;
     this.httpVerbMap        = httpVerbMap;
     this.httpContextStorage = httpContextStorage;
 }
Esempio n. 19
0
 public ApplyPaginationByClientRequestObserver(
     PaginationOptions options,
     IPaginationByClientRequestInterpreter interpreter,
     IScopedStorage <PaginationInfo> paginationInfoStorage,
     IObserver <IQueryable <TSource> > child,
     IDisposable disposable)
     : base(child, disposable)
 {
     this.options               = options;
     this.interpreter           = interpreter;
     this.paginationInfoStorage = paginationInfoStorage;
 }
 public MapToRestCollectionObserver(
     Func <TSource, TTarget> mapping,
     IRestCollectionGenerator <TSource, TTarget> restCollectionGenerator,
     IScopedStorage <PaginationInfo> paginationInfoStorage,
     IObserver <IRestEntity> child,
     IDisposable disposable)
     : base(child, disposable)
 {
     this.mapping = mapping;
     this.restCollectionGenerator = restCollectionGenerator;
     this.paginationInfoStorage   = paginationInfoStorage;
 }
 public PaginationByClientRequestPipe(
     PaginationOptions options,
     IPaginationByClientRequestInterpreter interpreter,
     IScopedStorage <PaginationMetaInfo> paginationMetaInfoStorage,
     IQueryableTransformer <TInput> queryableTransformer,
     IOutputPipe <IQueryable <TInput> > parent)
     : base(parent)
 {
     this.options     = options ?? new PaginationOptions();
     this.interpreter = interpreter;
     this.paginationMetaInfoStorage = paginationMetaInfoStorage;
     this.queryableTransformer      = queryableTransformer;
 }
 public CollectionMappingPipe(
     Func <TInput, TOutput> mapping,
     IRestCollectionLinkGenerator linkGenerator,
     IScopedStorage <PaginationMetaInfo> paginationMetaInfoStorage,
     IQueryableTransformer <TInput> queryableTransformer,
     IOutputPipe <IQueryable <TInput> > parent)
     : base(parent)
 {
     this.mapping                   = mapping;
     this.linkGenerator             = linkGenerator;
     this.paginationMetaInfoStorage = paginationMetaInfoStorage;
     this.queryableTransformer      = queryableTransformer;
 }
 public EntityFrameworkPersistedGrantStoreEx(
     IScopedHttpContextRequestForm scopedHttpContextRequestForm,
     IScopedContext <TenantRequestContext> scopedTenantRequestContext,
     IScopedStorage scopedStorage,
     IAdminServices adminServices,
     IEntityFrameworkMapperAccessor entityFrameworkMapperAccessor,
     ITenantAwareConfigurationDbContextAccessor tenantAwareConfigurationDbContextAccessor,
     ILogger <EntityFrameworkPersistedGrantStoreEx> logger)
 {
     _scopedHttpContextRequestForm = scopedHttpContextRequestForm;
     _scopedTenantRequestContext   = scopedTenantRequestContext;
     _scopedStorage = scopedStorage;
     _adminServices = adminServices;
     _entityFrameworkMapperAccessor             = entityFrameworkMapperAccessor;
     _tenantAwareConfigurationDbContextAccessor = tenantAwareConfigurationDbContextAccessor;
     Logger = logger;
 }
        public InMemoryTenantAwarePersistedGrantStore(
            IScopedStorage scopedStorage,
            IScopedContext <TenantRequestContext> scopedTenantRequestContext,
            ICoreMapperAccessor coreMapperAccessor)
        {
            _scopedStorage = scopedStorage;
            _scopedTenantRequestContext = scopedTenantRequestContext;
            _coreMapperAccessor         = coreMapperAccessor;
            if (!string.IsNullOrWhiteSpace(_scopedTenantRequestContext.Context.TenantName))
            {
                if (!_tenantStores.ContainsKey(_scopedTenantRequestContext.Context.TenantName))
                {
                    _tenantStores.TryAdd(_scopedTenantRequestContext.Context.TenantName, new InMemoryPersistedGrantStore());
                }

                _tenantStores.TryGetValue(_scopedTenantRequestContext.Context.TenantName, out _innerPersistedGrantStore);
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Invokes the middleware.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="router">The router.</param>
        /// <param name="session">The user session.</param>
        /// <param name="events">The event service.</param>
        /// <returns></returns>
        public async Task Invoke(
            HttpContext context,
            IEndpointRouter router,
            IUserSession session,
            IEventService events,
            IScopedStorage scopedStorage)
        {
            scopedStorage.Storage["IdentityServer:Handled"] = false;
            // this will check the authentication session and from it emit the check session
            // cookie needed from JS-based signout clients.
            await session.EnsureSessionIdCookieAsync();

            try
            {
                var endpoint = router.Find(context);
                if (endpoint != null)
                {
                    _logger.LogInformation("Invoking IdentityServer endpoint: {endpointType} for {url}", endpoint.GetType().FullName, context.Request.Path.ToString());

                    var result = await endpoint.ProcessAsync(context);

                    if (result != null)
                    {
                        _logger.LogTrace("Invoking result: {type}", result.GetType().FullName);
                        // await result.ExecuteAsync(context);
                        scopedStorage.Storage["IEndpointResult"]        = result;
                        scopedStorage.Storage["IdentityServer:Handled"] = true;
                    }
                }
            }
            catch (Exception ex)
            {
                await events.RaiseAsync(new UnhandledExceptionEvent(ex));

                _logger.LogCritical(ex, "Unhandled exception: {exception}", ex.Message);
                throw;
            }

            await _next(context);
        }
Esempio n. 26
0
 public MyTokenResponseGenerator(
     IScopedHttpContextRequestForm scopedHttpContextRequestForm,
     IHttpContextAccessor contextAccessor,
     IScopedOptionalClaims scopedOptionalClaims,
     IScopedStorage scopedStorage,
     IRefreshTokenStore refreshTokenStore,
     IReferenceTokenStore referenceTokenStore,
     IPersistedGrantStoreEx persistedGrantStore,
     ISystemClock clock,
     ITokenService tokenService,
     IRefreshTokenService refreshTokenService,
     IScopeParser scopeParser,
     IResourceStore resources,
     IClientStore clients,
     ILogger <TokenResponseGenerator> logger) : base(clock, tokenService, refreshTokenService, scopeParser, resources, clients, logger)
 {
     _scopedHttpContextRequestForm = scopedHttpContextRequestForm;
     _contextAccessor      = contextAccessor;
     _scopedOptionalClaims = scopedOptionalClaims;
     _refreshTokenStore    = refreshTokenStore;
     _referenceTokenStore  = referenceTokenStore;
     _scopedStorage        = scopedStorage;
     _persistedGrantStore  = persistedGrantStore;
 }
Esempio n. 27
0
 public EntityInsertionPipeFactory(DbContext context, IScopedStorage <TInput> entityStorage)
 {
     this.context       = context;
     this.entityStorage = entityStorage;
 }
Esempio n. 28
0
 public IContext create_for(IScopedStorage storage)
 {
     return new Context(storage.provide_storage());
 }
        public async Task ValidateAsync(CustomTokenRequestValidationContext context)
        {
            IScopedStorage _scopedStorage = _serviceProvider.GetService(typeof(IScopedStorage)) as IScopedStorage;
            var            identityServerRequestRecord =
                _scopedStorage.Storage["IdentityServerRequestRecord"] as IdentityServerRequestRecord;

            var raw   = context.Result.ValidatedRequest.Raw;
            var rr    = raw.AllKeys.ToDictionary(k => k, k => raw[(string)k]);
            var error = false;
            var los   = new List <string>();

            /*
             * var oneMustExistResult = (from item in OneMustExitsArguments
             *  where rr.Keys.Contains(item)
             *  select item).ToList();
             *
             * if (!oneMustExistResult.Any())
             * {
             *  error = true;
             *  los.AddRange(OneMustExitsArguments.Select(item => $"[one or the other] {item} is missing!"));
             * }
             */
            var result = RequiredArbitraryArguments.Except(rr.Keys);

            if (result.Any())
            {
                error = true;
                los.AddRange(result.Select(item => $"{item} is missing!"));
            }

            // make sure nothing is malformed
            error = los.ValidateFormat <Dictionary <string, List <string> > >(Constants.ArbitraryClaims, raw[Constants.ArbitraryClaims]) || error;
            error = los.ValidateFormat <List <string> >(Constants.ArbitraryAmrs, raw[Constants.ArbitraryAmrs]) || error;
            error = los.ValidateFormat <List <string> >(Constants.ArbitraryAudiences, raw[Constants.ArbitraryAudiences]) || error;

            if (!error)
            {
                var arbitraryClaims = raw[Constants.ArbitraryClaims];
                if (!string.IsNullOrWhiteSpace(arbitraryClaims))
                {
                    var values =
                        JsonConvert.DeserializeObject <Dictionary <string, List <string> > >(arbitraryClaims);
                    var invalidClaims = (from o in values
                                         join p in NotAllowedArbitraryClaims on o.Key equals p into t
                                         from od in t.DefaultIfEmpty()
                                         where od != null
                                         select od).ToList();
                    if (invalidClaims.Any())
                    {
                        // not allowed.
                        error = true;
                        foreach (var invalidClaim in invalidClaims)
                        {
                            los.Add($"The arbitrary claim: '{invalidClaim}' is not allowed.");
                        }
                    }
                }
            }
            if (!error)
            {
                var customPayload = raw[Constants.CustomPayload];
                if (!string.IsNullOrWhiteSpace(customPayload))
                {
                    error = !customPayload.IsValidJson();
                    if (error)
                    {
                        los.Add($"{Constants.CustomPayload} is not valid: '{customPayload}'.");
                    }
                }
            }
            if (error)
            {
                context.Result.IsError = true;
                context.Result.Error   = String.Join <string>(" | ", los);
            }
        }
 public AllowedOptionsBuilder(IScopedStorage <HttpContext> httpContextStorage)
 {
     this.claimsPrincipal = httpContextStorage.Value.User;
 }
 public ClaimValidationPipeFactory(IScopedStorage <HttpContext> httpContextStorage)
 {
     this.user = httpContextStorage.Value.User;
 }