コード例 #1
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (JWToken.Length != 0)
            {
                hash ^= JWToken.GetHashCode();
            }
            if (reservation_ != null)
            {
                hash ^= Reservation.GetHashCode();
            }
            if (guestId_ != null)
            {
                hash ^= GuestId.GetHashCode();
            }
            if (penalty_ != null)
            {
                hash ^= Penalty.GetHashCode();
            }
            if (DaysBeforeReservationStart != 0)
            {
                hash ^= DaysBeforeReservationStart.GetHashCode();
            }
            if (RequestingParty.Length != 0)
            {
                hash ^= RequestingParty.GetHashCode();
            }
            return(hash);
        }
コード例 #2
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (JWToken.Length != 0)
            {
                hash ^= JWToken.GetHashCode();
            }
            if (opsdate_ != null)
            {
                hash ^= Opsdate.GetHashCode();
            }
            if (pretaxLodgingCharge_ != null)
            {
                hash ^= PretaxLodgingCharge.GetHashCode();
            }
            if (roomTypeId_ != null)
            {
                hash ^= RoomTypeId.GetHashCode();
            }
            if (guestId_ != null)
            {
                hash ^= GuestId.GetHashCode();
            }
            if (reservationId_ != null)
            {
                hash ^= ReservationId.GetHashCode();
            }
            return(hash);
        }
コード例 #3
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (JWToken.Length != 0)
            {
                hash ^= JWToken.GetHashCode();
            }
            if (reservation_ != null)
            {
                hash ^= Reservation.GetHashCode();
            }
            if (priceQuote_ != null)
            {
                hash ^= PriceQuote.GetHashCode();
            }
            if (reservationSummary_ != null)
            {
                hash ^= ReservationSummary.GetHashCode();
            }
            if (HasLastMinuteWaiver != false)
            {
                hash ^= HasLastMinuteWaiver.GetHashCode();
            }
            return(hash);
        }
コード例 #4
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (JWToken.Length != 0)
            {
                hash ^= JWToken.GetHashCode();
            }
            if (room_ != null)
            {
                hash ^= Room.GetHashCode();
            }
            if (reservation_ != null)
            {
                hash ^= Reservation.GetHashCode();
            }
            if (IsNewKey != false)
            {
                hash ^= IsNewKey.GetHashCode();
            }
            if (QuantityIssued != 0)
            {
                hash ^= QuantityIssued.GetHashCode();
            }
            return(hash);
        }
コード例 #5
0
        public CompareResult CreateCompare()
        {
            //Get User from header token
            string userName;
            var    token = Request.Headers.FirstOrDefault(x => string.Equals(x.Key, "Authorization")).Value.ElementAt(0);

            JWToken.Validate(token, out userName);
            if (string.IsNullOrWhiteSpace(userName))
            {
                return(new CompareResult()
                {
                    Status = 3,
                    Message = "Authorization failed."
                });
            }

            string       config       = HttpContext.Current.Request["Config"];
            CompareInput compareInput = JsonConvert.DeserializeObject <CompareInput>(config);

            HttpFileCollection files = HttpContext.Current.Request.Files;

            if (files.AllKeys.Length != 2)
            {
                return(new CompareResult()
                {
                    Status = 3,
                    Message = "Error Input"
                });
            }

            compareInput.FileName1 = SaveFile(files[0]);
            compareInput.FileName2 = SaveFile(files[1]);

            return(CompareSvc.Start(userName, compareInput));
        }
        public override int GetHashCode()
        {
            int hash = 1;

            if (JWToken.Length != 0)
            {
                hash ^= JWToken.GetHashCode();
            }
            if (reservation_ != null)
            {
                hash ^= Reservation.GetHashCode();
            }
            if (ReservationHadGuaranteeTender != false)
            {
                hash ^= ReservationHadGuaranteeTender.GetHashCode();
            }
            if (reservationSummary_ != null)
            {
                hash ^= ReservationSummary.GetHashCode();
            }
            if (priceQuote_ != null)
            {
                hash ^= PriceQuote.GetHashCode();
            }
            return(hash);
        }
コード例 #7
0
 public LoginController(IConfiguration config, IRepositoryWrapper repository, ILoggerManager logger)
 {
     _config     = config;
     _repository = repository;
     _logger     = logger;
     JWT         = new JWToken(config);
     hash        = new Bcrypt(repository);
 }
コード例 #8
0
ファイル: Session.cs プロジェクト: joseplj/GabberMobile
 public static void NukeItFromOrbit()
 {
     ActiveUser = null;
     Token      = null;
     Connection.DropTable <User>();
     Connection.DropTable <Project>();
     Connection.DropTable <InterviewSession>();
     Connection.DropTable <InterviewPrompt>();
     Connection.DropTable <LanguageChoice>();
     _connection = null;
 }
        public override int GetHashCode()
        {
            int hash = 1;

            if (JWToken.Length != 0)
            {
                hash ^= JWToken.GetHashCode();
            }
            if (reservation_ != null)
            {
                hash ^= Reservation.GetHashCode();
            }
            return(hash);
        }
コード例 #10
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (JWToken.Length != 0)
            {
                hash ^= JWToken.GetHashCode();
            }
            if (groupBooking_ != null)
            {
                hash ^= GroupBooking.GetHashCode();
            }
            return(hash);
        }
コード例 #11
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (JWToken.Length != 0)
            {
                hash ^= JWToken.GetHashCode();
            }
            if (propertyId_ != null)
            {
                hash ^= PropertyId.GetHashCode();
            }
            return(hash);
        }
コード例 #12
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (JWToken.Length != 0)
            {
                hash ^= JWToken.GetHashCode();
            }
            if (groupBooking_ != null)
            {
                hash ^= GroupBooking.GetHashCode();
            }
            hash ^= roomTypeQuantities_.GetHashCode();
            return(hash);
        }
コード例 #13
0
        public List <CompareResult> GetCompareHistroy(int start, int count)
        {
            //Get User from header token
            string userName;
            var    token = Request.Headers.FirstOrDefault(x => string.Equals(x.Key, "Authorization")).Value.ElementAt(0);

            JWToken.Validate(token, out userName);
            if (string.IsNullOrWhiteSpace(userName))
            {
                return(new List <CompareResult>());
            }


            return(CompareSvc.GetCompareHistory(userName, start, count));
        }
コード例 #14
0
        private object SessionLoginWithToken(IList args, IPEndPoint remoteClient)
        {
            UUID sessionId;
            var  token = new JWToken((string)args[0], m_sigUtil);

            if (token.Payload.Scope != "remote-admin")
            {
                throw new Exception("Invalid Token Scope");
            }

            lock (m_activeSessions)
            {
                sessionId = UUID.Random();
                m_activeSessions.Add(sessionId, DateTime.Now);
            }

            return(sessionId.ToString());
        }
コード例 #15
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (JWToken.Length != 0)
            {
                hash ^= JWToken.GetHashCode();
            }
            if (TerminalIdentifier.Length != 0)
            {
                hash ^= TerminalIdentifier.GetHashCode();
            }
            if (StatusCode.Length != 0)
            {
                hash ^= StatusCode.GetHashCode();
            }
            return(hash);
        }
        public override int GetHashCode()
        {
            int hash = 1;

            if (JWToken.Length != 0)
            {
                hash ^= JWToken.GetHashCode();
            }
            if (bookingReservation_ != null)
            {
                hash ^= BookingReservation.GetHashCode();
            }
            if (incidentalReservation_ != null)
            {
                hash ^= IncidentalReservation.GetHashCode();
            }
            return(hash);
        }
コード例 #17
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (JWToken.Length != 0)
            {
                hash ^= JWToken.GetHashCode();
            }
            if (CrudAction != 0)
            {
                hash ^= CrudAction.GetHashCode();
            }
            if (roomType_ != null)
            {
                hash ^= RoomType.GetHashCode();
            }
            return(hash);
        }
コード例 #18
0
ファイル: RemoteAdmin.cs プロジェクト: lbgrid/halcyon
        private object SessionLoginWithToken(IList args, IPEndPoint remoteClient)
        {
            UUID sessionId;
            var  token = new JWToken((string)args[0], m_sigUtil);

            if (!(token.HasValidSignature && token.IsNotExpired && token.Payload.Scope == "remote-admin"))
            {
                throw new Exception("Invalid Token");
            }
            else
            {
                lock (m_activeSessions)
                {
                    sessionId = UUID.Random();
                    m_activeSessions.Add(sessionId, DateTime.Now);
                }
            }

            return(sessionId.ToString());
        }
コード例 #19
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (JWToken.Length != 0)
            {
                hash ^= JWToken.GetHashCode();
            }
            if (room_ != null)
            {
                hash ^= Room.GetHashCode();
            }
            if (reservation_ != null)
            {
                hash ^= Reservation.GetHashCode();
            }
            if (OccupancyPrematerializedOnReservation != false)
            {
                hash ^= OccupancyPrematerializedOnReservation.GetHashCode();
            }
            return(hash);
        }
コード例 #20
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (JWToken.Length != 0)
            {
                hash ^= JWToken.GetHashCode();
            }
            if (RawMsg.Length != 0)
            {
                hash ^= RawMsg.GetHashCode();
            }
            if (msgReceivedAt_ != null)
            {
                hash ^= MsgReceivedAt.GetHashCode();
            }
            if (mitelCallEnded_ != null)
            {
                hash ^= MitelCallEnded.GetHashCode();
            }
            return(hash);
        }
        public override int GetHashCode()
        {
            int hash = 1;

            if (JWToken.Length != 0)
            {
                hash ^= JWToken.GetHashCode();
            }
            if (reservation_ != null)
            {
                hash ^= Reservation.GetHashCode();
            }
            if (guestId_ != null)
            {
                hash ^= GuestId.GetHashCode();
            }
            if (ReservationBookingNumber.Length != 0)
            {
                hash ^= ReservationBookingNumber.GetHashCode();
            }
            return(hash);
        }
コード例 #22
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (JWToken.Length != 0)
            {
                hash ^= JWToken.GetHashCode();
            }
            if (CrudAction != 0)
            {
                hash ^= CrudAction.GetHashCode();
            }
            if (before_ != null)
            {
                hash ^= Before.GetHashCode();
            }
            if (after_ != null)
            {
                hash ^= After.GetHashCode();
            }
            return(hash);
        }
        public override int GetHashCode()
        {
            int hash = 1;

            if (JWToken.Length != 0)
            {
                hash ^= JWToken.GetHashCode();
            }
            if (reservation_ != null)
            {
                hash ^= Reservation.GetHashCode();
            }
            if (checkInDate_ != null)
            {
                hash ^= CheckInDate.GetHashCode();
            }
            if (roomId_ != null)
            {
                hash ^= RoomId.GetHashCode();
            }
            if (guestId_ != null)
            {
                hash ^= GuestId.GetHashCode();
            }
            if (averageRate_ != null)
            {
                hash ^= AverageRate.GetHashCode();
            }
            if (ReservationBookingNumber.Length != 0)
            {
                hash ^= ReservationBookingNumber.GetHashCode();
            }
            if (KeepGuaranteeRequested != false)
            {
                hash ^= KeepGuaranteeRequested.GetHashCode();
            }
            return(hash);
        }
コード例 #24
0
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            //如果用户方位的Action带有AllowAnonymousAttribute,则不进行授权验证
            if (actionContext.ActionDescriptor.GetCustomAttributes <AllowAnonymousAttribute>().Any())
            {
                return;
            }



            var tokenElements = actionContext.Request.Headers.FirstOrDefault(x => string.Equals(x.Key, "Authorization")).Value;

            if (tokenElements != null)
            {
                var    token = tokenElements.ElementAt(0);
                string temp;
                if (JWToken.Validate(token, out temp))
                {
                    return;
                }
            }

            actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, new HttpError("Authorization failed"));
        }
コード例 #25
0
ファイル: RemoteConsole.cs プロジェクト: lbgrid/halcyon
        private Hashtable HandleHttpStartSession(Hashtable request)
        {
            DoExpire();

            Hashtable post  = DecodePostString(request["body"].ToString());
            Hashtable reply = new Hashtable();

            reply["str_response_string"] = String.Empty;
            reply["int_response_code"]   = 401;
            reply["content_type"]        = "text/plain";

            var headers = (Hashtable)request["headers"];

            if (headers.ContainsKey("Authorization"))
            {
                var authHeader = headers["Authorization"].ToString();
                if (!authHeader.StartsWith("Bearer ", StringComparison.InvariantCultureIgnoreCase))
                {
                    m_log.Warn($"[REMOTECONSOLE] StartSession JWT Authorization header format failure from '{headers["remote_addr"]}'.");
                    return(reply);
                }

                try
                {
                    var token = new JWToken(authHeader.Substring(7), m_sigUtil);

                    // TODO: Make the scope strings come from some central list that can be registered into?
                    if (!(token.HasValidSignature && token.IsNotExpired && token.Payload.Scope == "remote-console"))
                    {
                        m_log.Warn($"[REMOTECONSOLE] StartSession invalid/expired/wrong scope JWToken from '{headers["remote_addr"]}'.");
                        return(reply);
                    }

                    m_log.Info($"[REMOTECONSOLE] StartSession access granted via JWT to '{token.Payload.Username}' from '{headers["remote_addr"]}'.");
                }
                catch (JWTokenException jte)
                {
                    m_log.Error($"[REMOTECONSOLE] Failure with JWToken in StartSession from '{headers["remote_addr"]}': {jte}");
                    return(reply);
                }
            }
            else if (request.ContainsKey("USER") && request.ContainsKey("PASS"))
            {
                string username = post["USER"].ToString();
                string password = post["PASS"].ToString();

                // Validate the username/password pair
                if (Util.AuthenticateAsSystemUser(username, password) == false)
                {
                    return(reply);
                }

                m_log.Warn($"[REMOTECONSOLE] StartSession access granted via legacy system username and password to '{username}' from '{headers["remote_addr"]}'.");
            }
            else
            {
                return(reply);
            }

            ConsoleConnection c = new ConsoleConnection();

            c.last         = System.Environment.TickCount;
            c.lastLineSeen = 0;

            UUID sessionID = UUID.Random();

            lock (m_Connections)
            {
                m_Connections[sessionID] = c;
            }

            string          uri     = "/ReadResponses/" + sessionID.ToString() + "/";
            IRequestHandler handler = new AsyncRequestHandler("POST", uri, AsyncReadResponses);

            m_Server.AddStreamHandler(handler);

            XmlDocument xmldoc  = new XmlDocument();
            XmlNode     xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, String.Empty, String.Empty);

            xmldoc.AppendChild(xmlnode);
            XmlElement rootElement = xmldoc.CreateElement(String.Empty, "ConsoleSession", String.Empty);

            xmldoc.AppendChild(rootElement);

            XmlElement id = xmldoc.CreateElement(String.Empty, "SessionID", String.Empty);

            id.AppendChild(xmldoc.CreateTextNode(sessionID.ToString()));

            rootElement.AppendChild(id);

            XmlElement prompt = xmldoc.CreateElement(String.Empty, "Prompt", String.Empty);

            prompt.AppendChild(xmldoc.CreateTextNode(DefaultPrompt));

            rootElement.AppendChild(prompt);

            rootElement.AppendChild(MainConsole.Instance.Commands.GetXml(xmldoc));

            reply["str_response_string"] = xmldoc.InnerXml;
            reply["int_response_code"]   = 200;
            reply["content_type"]        = "text/xml";
            reply = CheckOrigin(reply);

            return(reply);
        }
コード例 #26
0
ファイル: RemoteConsole.cs プロジェクト: lbgrid/halcyon
        private Hashtable HandleHttpSessionCommand(Hashtable request)
        {
            DoExpire();

            Hashtable post  = DecodePostString(request["body"].ToString());
            Hashtable reply = new Hashtable();

            reply["str_response_string"] = String.Empty;
            reply["int_response_code"]   = 404;
            reply["content_type"]        = "text/plain";

            var headers = (Hashtable)request["headers"];

            if (headers.ContainsKey("Authorization"))
            {
                var authHeader = headers["Authorization"].ToString();
                if (!authHeader.StartsWith("Bearer ", StringComparison.InvariantCultureIgnoreCase))
                {
                    m_log.Warn($"[REMOTECONSOLE] SessionCommand JWT Authorization header format failure from '{headers["remote_addr"]}'.");
                    return(reply);
                }

                try
                {
                    var token = new JWToken(authHeader.Substring(7), m_sigUtil);

                    // TODO: Make the scope strings come from some central list that can be registered into?
                    if (!(token.HasValidSignature && token.IsNotExpired && token.Payload.Scope == "remote-console"))
                    {
                        m_log.Warn($"[REMOTECONSOLE] SessionCommand invalid/expired/wrong scope JWToken from '{headers["remote_addr"]}'.");
                        return(reply);
                    }

                    m_log.Info($"[REMOTECONSOLE] SessionCommand for session '{post["ID"]}' accessed via JWT by '{token.Payload.Username}' from '{headers["remote_addr"]}' with command '{post["COMMAND"]}'.");
                }
                catch (JWTokenException jte)
                {
                    m_log.Error($"[REMOTECONSOLE] Failure with JWToken in SessionCommand from '{headers["remote_addr"]}': {jte}");
                    return(reply);
                }
            }
            else
            {
                m_log.Warn($"[REMOTECONSOLE] SessionCommand for session '{post["ID"]}' from '{headers["remote_addr"]}' being accessed without Authorization header!");
            }
            // BUG: Longstanding issue: if someone gets ahold of, or guesses, the ID of another user they can send comamnds to the console.
            // The only way I can think to close this bug is to associate each session with something the user cannot change. Not sure, but maybe the IP address of the connection would work?

            if (post["ID"] == null)
            {
                return(reply);
            }

            UUID id;

            if (!UUID.TryParse(post["ID"].ToString(), out id))
            {
                return(reply);
            }

            lock (m_Connections)
            {
                if (!m_Connections.ContainsKey(id))
                {
                    return(reply);
                }
            }

            if (post["COMMAND"] == null)
            {
                return(reply);
            }

            lock (m_InputData)
            {
                m_DataEvent.Set();
                m_InputData.Add(post["COMMAND"].ToString());
            }

            XmlDocument xmldoc  = new XmlDocument();
            XmlNode     xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, String.Empty, String.Empty);

            xmldoc.AppendChild(xmlnode);
            XmlElement rootElement = xmldoc.CreateElement(String.Empty, "ConsoleSession", String.Empty);

            xmldoc.AppendChild(rootElement);

            XmlElement res = xmldoc.CreateElement(String.Empty, "Result", String.Empty);

            res.AppendChild(xmldoc.CreateTextNode("OK"));

            rootElement.AppendChild(res);

            reply["str_response_string"] = xmldoc.InnerXml;
            reply["int_response_code"]   = 200;
            reply["content_type"]        = "text/xml";
            reply = CheckOrigin(reply);

            return(reply);
        }
コード例 #27
0
ファイル: RemoteConsole.cs プロジェクト: lbgrid/halcyon
        public void AsyncReadResponses(IHttpServer server, string path, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            int    pos1    = path.IndexOf("/");           // /ReadResponses
            int    pos2    = path.IndexOf("/", pos1 + 1); // /ReadResponses/
            int    pos3    = path.IndexOf("/", pos2 + 1); // /ReadResponses/<UUID>/
            int    len     = pos3 - pos2 - 1;
            string uri_tmp = path.Substring(pos2 + 1, len);

            var authHeader = httpRequest.Headers.Get("Authorization");

            if (authHeader != null)
            {
                if (!authHeader.StartsWith("Bearer ", StringComparison.InvariantCultureIgnoreCase))
                {
                    m_log.Warn($"[REMOTECONSOLE] ReadResponses JWT Authorization header format failure from '{httpRequest.RemoteIPEndPoint}'.");
                    return;
                }

                try
                {
                    var token = new JWToken(authHeader.Substring(7), m_sigUtil);

                    // TODO: Make the scope strings come from some central list that can be registered into?
                    if (!(token.HasValidSignature && token.IsNotExpired && token.Payload.Scope == "remote-console"))
                    {
                        m_log.Warn($"[REMOTECONSOLE] ReadResponses invalid/expired/wrong scope JWToken from '{httpRequest.RemoteIPEndPoint}'.");
                        return;
                    }

                    m_log.Info($"[REMOTECONSOLE] ReadResponses for session '{uri_tmp}' accessed via JWT by '{token.Payload.Username}' from '{httpRequest.RemoteIPEndPoint}'.");
                }
                catch (JWTokenException jte)
                {
                    m_log.Error($"[REMOTECONSOLE] Failure with JWToken in ReadResponses from '{httpRequest.RemoteIPEndPoint}': {jte}");
                    return;
                }
            }
            else
            {
                m_log.Warn($"[REMOTECONSOLE] ReadResponses for session '{uri_tmp}' from '{httpRequest.RemoteIPEndPoint}' being accessed without Authorization header!");
            }
            // BUG: Longstanding issue: if someone gets ahold of, or guesses, the ID of another user they can send comamnds to the console.
            // The only way I can think to close this bug is to associate each session with something the user cannot change. Not sure, but maybe the IP address of the connection would work?

            UUID sessionID;

            if (UUID.TryParse(uri_tmp, out sessionID) == false)
            {
                return;
            }

            // Create the new request
            AsyncHttpRequest newRequest =
                new AsyncHttpRequest(server, httpRequest, httpResponse, sessionID, TimeoutHandler, 60 * 1000);
            AsyncHttpRequest currentRequest = null;

            lock (m_Connections)
            {
                ConsoleConnection connection = null;
                m_Connections.TryGetValue(sessionID, out connection);
                if (connection == null)
                {
                    return;
                }

                currentRequest     = connection.request;
                connection.request = newRequest;
            }

            // If there was a request already posted, signal it.
            if (currentRequest != null)
            {
                currentRequest.SendResponse(ProcessEvents(currentRequest));
            }
        }
コード例 #28
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOptions();
            // https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/dependency-injection
            services.Configure <EnabledRules>(_configuration.GetSection("EnabledRules"));
            services.Configure <Settings>(_configuration.GetSection("Thermostat"));
            services.Configure <AccountSettings>(_configuration.GetSection("Account"));

            // Uncomment to add settings from code
            //services.Configure<SampleWebSettings>(settings =>
            //{
            //    oauthCodes = new Dictionary
            //    settings.Updates = 17;
            //});

            //call this in case you need aspnet-user-authtype/aspnet-user-identity
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            //services.AddSingleton(_configuration);
            services.AddSingleton <OAuthCodeStore>();

            // add repository as a service
            services.AddTransient <Repository>();
            services.AddSingleton(_engine);

            // Add framework services.
            services.AddApplicationInsightsTelemetry(_configuration);

            services.AddMvc().AddJsonOptions(options =>
            {
                //options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
                options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
            });
            //services.Configure<IISOptions>( options => options.)

            services.AddAuthorization(options =>
            {
                options.AddPolicy("passport", policy => policy.RequireClaim("passport"));
            });

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(o =>
            {
                o.LoginPath        = new PathString("/Account/Login");
                o.AccessDeniedPath = new PathString("/Account/Forbidden/");
                o.Cookie.Name      = "cookie";
            });

            // add Alexa JWT token validation
            //TOOD: create a separate nuget for that
            services.AddAuthorization(options =>
            {
                options.AddPolicy("AlexaJWT",
                                  policy => policy.RequireAssertion(context =>
                {
                    if (context.Resource is Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext mvcContext)
                    {
                        // Examine MVC specific things like routing data.
                        var tokenData = mvcContext.HttpContext.Request.Query["accessToken"].FirstOrDefault();
                        if (tokenData == null)
                        {
                            return(false);
                        }

                        JWToken token = JsonConvert.DeserializeObject <JWToken>(tokenData);

                        //TODO: something else..
                        return(token.Validate(_configuration.GetSection("Account").GetValue <string>("TokenKey")));
                    }
                    return(false);
                }
                                                                    ));
            });

            // Add our BackgroundService which will be saving telemetry at regular intervals
            services.AddSingleton <IHostedService, BackgroundService>();

            // Note .AddMiniProfiler() returns a IMiniProfilerBuilder for easy intellisense
            services.AddMiniProfiler(options =>
            {
                // All of this is optional. You can simply call .AddMiniProfiler() for all defaults

                // (Optional) Path to use for profiler URLs, default is /mini-profiler-resources
                options.RouteBasePath = "/profiler";

                // (Optional) Control storage
                // (default is 30 minutes in MemoryCacheStorage)
                //(options.Storage as MemoryCacheStorage).CacheDuration = TimeSpan.FromMinutes(60);

                // (Optional) Control which SQL formatter to use, InlineFormatter is the default
                options.SqlFormatter = new StackExchange.Profiling.SqlFormatters.InlineFormatter();

                // (Optional) To control authorization, you can use the Func<HttpRequest, bool> options:
                // (default is everyone can access profilers)
                //options.ResultsAuthorize = request => MyGetUserFunction(request).CanSeeMiniProfiler;
                //options.ResultsListAuthorize = request => MyGetUserFunction(request).CanSeeMiniProfiler;

                // (Optional)  To control which requests are profiled, use the Func<HttpRequest, bool> option:
                // (default is everything should be profiled)
                //options.ShouldProfile = request => MyShouldThisBeProfiledFunction(request);

                // (Optional) Profiles are stored under a user ID, function to get it:
                // (default is null, since above methods don't use it by default)
                //options.UserIdProvider = request => MyGetUserIdFunction(request);

                // (Optional) Swap out the entire profiler provider, if you want
                // (default handles async and works fine for almost all appliations)
                //options.ProfilerProvider = new MyProfilerProvider();
            });
        }
コード例 #29
0
        private Hashtable HandleHttpCloseSession(Hashtable request)
        {
            DoExpire();

            var post  = DecodePostString(request["body"].ToString());
            var reply = new Hashtable();

            reply["str_response_string"] = string.Empty;
            reply["int_response_code"]   = 404;
            reply["content_type"]        = "text/plain";

            JWToken token   = null;
            var     headers = (Hashtable)request["headers"];

            if (headers.ContainsKey("Authorization"))
            {
                var authHeader = headers["Authorization"].ToString();
                if (!authHeader.StartsWith("Bearer ", StringComparison.InvariantCultureIgnoreCase))
                {
                    m_log.Warn($"[REMOTECONSOLE] CloseSession JWT Authorization header format failure from '{headers["remote_addr"]}'.");
                    return(reply);
                }

                if (m_sigUtil == null)
                {
                    m_log.Warn("[REMOTECONSOLE] CloseSession JWT Authorization subsystem not initialized. Does your Halcyon.ini contain a SSLCertFile stanza in the [Network] section?");
                    return(reply);
                }

                try
                {
                    token = new JWToken(authHeader.Substring(7), m_sigUtil);

                    // TODO: Make the scope strings come from some central list that can be registered into?
                    if (token.Payload.Scope != "remote-console")
                    {
                        m_log.Warn($"[REMOTECONSOLE] CloseSession wrong scope JWToken from '{headers["remote_addr"]}'.");
                        return(reply);
                    }

                    m_log.Info($"[REMOTECONSOLE] CloseSession for session '{post["ID"]}' accessed via JWT by '{token.Payload.Username}' from '{headers["remote_addr"]}'.");
                }
                catch (JWTokenException jte)
                {
                    m_log.Error($"[REMOTECONSOLE] Failure with JWToken in CloseSession from '{headers["remote_addr"]}': {jte}");
                    return(reply);
                }
            }
            else
            {
                m_log.Warn($"[REMOTECONSOLE] CloseSession for session '{post["ID"]}' from '{headers["remote_addr"]}' being accessed without Authorization header!");
            }
            // BUG: Longstanding issue: if someone gets ahold of, or guesses, the ID and/or JWT of another user they can close the console.
            // The only way I can think to close this bug is to associate each session with something the user cannot change. Not sure, but maybe the IP address of the connection would work?

            if (post["ID"] == null)
            {
                return(reply);
            }

            UUID id;

            if (!UUID.TryParse(post["ID"].ToString(), out id))
            {
                return(reply);
            }

            lock (m_Connections)
            {
                if (m_Connections.ContainsKey(id))
                {
                    ConsoleConnection connection = m_Connections[id];
                    m_Connections.Remove(id);
                    CloseConnection(id);
                    if (connection.request != null)
                    {
                        AsyncHttpRequest req = connection.request;
                        connection.request = null;
                        req.SendResponse(ProcessEvents(req));
                    }
                }
            }

            var xmldoc  = new XmlDocument();
            var xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, string.Empty, string.Empty);

            xmldoc.AppendChild(xmlnode);
            var rootElement = xmldoc.CreateElement(string.Empty, "ConsoleSession", string.Empty);

            xmldoc.AppendChild(rootElement);

            var res = xmldoc.CreateElement(string.Empty, "Result", string.Empty);

            res.AppendChild(xmldoc.CreateTextNode("OK"));

            rootElement.AppendChild(res);

            reply["str_response_string"] = xmldoc.InnerXml;
            reply["int_response_code"]   = 200;
            reply["content_type"]        = "text/xml";
            reply = CheckOrigin(reply);

            m_log.Info($"[REMOTECONSOLE] CloseSession successful for user '{token?.Payload.Username}' with session '{id}' from '{headers["remote_addr"]}'.");

            return(reply);
        }