예제 #1
0
        public Task Invoke(HttpContext context, ILogger <HeaderRoutingMiddleware> logger)
        {
            if (!"POST".Equals(context.Request.Method))
            {
                context.Response.StatusCode = StatusCodes.Status400BadRequest;
                return(Task.CompletedTask);
            }

            if (!"/".Equals(context.Request.Path))
            {
                logger.LogWarning("Request path does not match '/', instead it is {WorkerRequestPath}", context.Request.Path);

                context.Response.StatusCode = StatusCodes.Status400BadRequest;
                return(Task.CompletedTask);
            }

            StringValues task = context.Request.Headers[TaskHeaderName];

            if (task.Count != 1)
            {
                logger.LogWarning("Request Task header should contain one task {WorkerTasks}", task);

                context.Response.StatusCode = StatusCodes.Status400BadRequest;
                return(Task.CompletedTask);
            }

            logger.LogDebug("Routing the request to {SimpleRoutingPath}", task);

            context.Request.Path = $"/{task.Single()}";

            return(_next(context));
        }
예제 #2
0
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            StringValues token = "";

            if (!context.HttpContext.Request.Headers.TryGetValue("Authorization", out token))
            {
                context.Result = new UnauthorizedResult();
                return;
            }

            if (token.Count() != 1)
            {
                context.Result = new UnauthorizedResult();
                return;
            }

            var tokenStr = token.Single();

            var authToken = _context.Tokens.Find(tokenStr);

            if (authToken == null)
            {
                context.Result = new UnauthorizedResult();
                return;
            }

            if (authToken.Expires < DateTimeOffset.UtcNow.ToUnixTimeSeconds())
            {
                context.Result = new UnauthorizedResult();

                _context.Tokens.Remove(authToken);
                return;
            }
        }
예제 #3
0
 //Validating User Access before allowing to access API
 public Boolean ValidateUserToken(StringValues authorizationHeader)
 {
     try
     {
         var          token         = authorizationHeader.Single().Split(" ").Last();
         LoginService loginservice  = new LoginService(_config);
         string       tokenUsername = loginservice.ValidateToken(token);
         //defining hardcoded value for demo purpose only
         if (!tokenUsername.Equals("kirang"))
         {
             return(false);
         }
         return(true);
     }
     catch (NullReferenceException ex)
     {
         throw new NullReferenceException("No Login token found" + ex.Message);
     }
 }
예제 #4
0
        private static Uri BuildUri(StringValues hostHeader, string pathAndQuery)
        {
            if (hostHeader.Count != 1)
            {
                throw new InvalidOperationException("Invalid Host Header");
            }

            var hostString = new HostString(hostHeader.Single());

            if (!hostString.HasValue)
            {
                return(null);
            }

            var fullUri = $"http://{hostString.ToUriComponent()}{pathAndQuery}";
            var uri     = new Uri(fullUri);

            return(uri);
        }
예제 #5
0
        public HttpBoardContext(IHttpContextAccessor contextAccessor)
        {
            if (contextAccessor.HttpContext == null)
            {
                return;
            }

            StringValues boardHeader = contextAccessor.HttpContext.Request.Headers["x-board"];

            if (boardHeader == StringValues.Empty)
            {
                return;
            }

            if (boardHeader.Count > 1)
            {
                throw new ArgumentException("Only one boardId is allowed");
            }

            Id = boardHeader.Single();
        }
        public static object GetValue(this RouteSpecRequestParameter parameter, StringValues values)
        {
            if (parameter.In == ParameterLocation.Path)
            {
                throw new NotImplementedException("Path parameters validation are not implemented just yet.");
            }


            var style     = parameter.Style ?? GetDefaultStyle(parameter.In);
            var delimeter = GetDelimeter(style);
            var explode   = values.Count > 1;
            var type      = parameter.Schema.GetSchemaType();

            switch (type)
            {
            case OpenApiSchemaType.Any:
            case OpenApiSchemaType.String:
            case OpenApiSchemaType.Boolean:
            case OpenApiSchemaType.Integer:
            case OpenApiSchemaType.Number:
                return(ParseScalarValue(values, parameter.Schema));

            case OpenApiSchemaType.Array:
                return(explode
                                   ? ParseArrayValue(values, parameter.Schema)
                                   : ParseArrayValue(values.Single().Split(delimeter), parameter.Schema));

            case OpenApiSchemaType.Object:
                throw new NotImplementedException(ObjectNotSupported);

            case OpenApiSchemaType.Null:
                return(null);

            case OpenApiSchemaType.Combined:
                throw new NotSupportedException();

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
        /// <inheritdoc />
        public override void OnActionExecuting(ActionExecutingContext actionContext)
        {
            if (_names.Count == 0)
            {
                return;
            }

            KeyValuePair <string, StringValues>[] parameters =
                actionContext.HttpContext
                .Request
                .Query
                .Where(x => _names.Contains(x.Key))
                .ToArray();

            bool check0 =
                _names.All(x => parameters.Select(y => y.Key).Contains(x));

            bool check1 =
                parameters.All(x => x.Value
                               .SelectMany(y => y.Split(','))
                               .All(y => !string.IsNullOrEmpty(y) &&
                                    !string.IsNullOrWhiteSpace(y)));

            if (check0 && check1)
            {
                return;
            }

            actionContext.Result =
                new ContentResult
            {
                StatusCode  = (int)HttpStatusCode.BadRequest,
                ContentType = "text/plain",
                Content     =
                    _names.Count == 1
                            ? $"Parameter '{_names.Single()}' is required."
                            : $"Parameters [{string.Join(", ", _names)}] are required."
            };
        }
        public string GetCurrentToken(HttpContext httpContext)
        {
            StringValues authorizationHeader = httpContext.Request.Headers["authorization"];

            return(authorizationHeader == StringValues.Empty ? string.Empty : authorizationHeader.Single().Split(' ').Last());
        }