protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            var authHeader      = Request.HttpContext.Request.Headers["Authorization"].ToString();
            var authHeaderParts = authHeader.Split(' ');

            if (authHeaderParts.Length >= 2 &&
                authHeaderParts[0].ToLower() == "bearer")
            {
                var entity = _data.GetEndpointIdentityByApiKey(authHeaderParts[1]);

                if (entity != null)
                {
                    var identity = new GenericIdentity(entity.uid.ToString());
                    Request.HttpContext.Items.Add("Identity", entity);
                    Request.HttpContext.User = new ClaimsPrincipal(identity);
                    return(AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), "ApiKey")));
                }

                return(AuthenticateResult.Fail("Missing or malformed 'Authorization' header."));
            }

            return(AuthenticateResult.NoResult());
        }
Esempio n. 2
0
        public async Task OnWebsocketConnected(HttpContext context, WebSocket ws)
        {
            /* Check API Key */
            string[] pathSegments = context.Request.Path.ToString().Split('/');
            string   apiKey       = string.Empty;

            EndpointIdentity endpoint;

            if (context.Request.Query.ContainsKey("key"))
            {
                apiKey = context.Request.Query["key"];

                endpoint = db.GetEndpointIdentityByApiKey(apiKey);

                if (endpoint == null)
                {
                    /* API Key falsch! */
                    await ws.CloseAsync(WebSocketCloseStatus.PolicyViolation, "API Key invalid!", CancellationToken.None);

                    return;
                }
            }
            else
            {
                await ws.CloseAsync(WebSocketCloseStatus.PolicyViolation, "API Key invalid!", CancellationToken.None);

                return;
            }

            activeWebsockets.Add(new WebsocketInfo()
            {
                ws       = ws,
                endpoint = endpoint
            });

            var buffer = new byte[1024 * 4];

            /* Send Init Commands, if Timestamp is given */
            if (context.Request.Query.ContainsKey("since"))
            {
                string   sinceTS = context.Request.Query["since"];
                DateTime sinceTime;

                if (DateTime.TryParse(sinceTS, out sinceTime))
                {
                    /* Load Objects from Database which have been modified since given Timestamp */
                    var objService = (ObjectService)context.RequestServices.GetService(typeof(ObjectService));

                    var modObjects = objService.GetModifiedObjects(sinceTime, endpoint);

                    foreach (var emergencyObject in modObjects)
                    {
                        var msg = JsonConvert.SerializeObject(new EmergencyObjectMessage()
                        {
                            data           = emergencyObject.data,
                            header         = emergencyObject.header,
                            uid            = emergencyObject.uid,
                            messageTrigger = MessageSentTrigger.Init
                        });

                        var msgBytes = Encoding.UTF8.GetBytes(msg);

                        await ws.SendAsync(new ArraySegment <byte>(msgBytes, 0, msgBytes.Length), WebSocketMessageType.Text, true, CancellationToken.None);
                    }
                }
                else
                {
                    await ws.CloseAsync(WebSocketCloseStatus.ProtocolError, "Since Timestamp invalid!", CancellationToken.None);

                    return;
                }
            }

            WebSocketReceiveResult result;

            do
            {
                result = await ws.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);
            } while (!result.CloseStatus.HasValue);

            await ws.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
        }