예제 #1
0
 public override ValueTask <ConnectionStatus> OnConnectAsync(
     ISocketConnection connection,
     InitializeConnectionMessage message,
     CancellationToken cancellationToken)
 {
     InitializeConnectionMessage = message;
     return(new ValueTask <ConnectionStatus>(ConnectionStatus.Accept()));
 }
        // private readonly IAuthenticationSchemeProvider _schemes;
        // public AuthenticationSocketInterceptor(IAuthenticationSchemeProvider schemes)
        // {
        //     _schemes = schemes;
        // }

        // public async Task<ConnectionStatus> OnOpenAsync(
        //     HttpContext context,
        //     IReadOnlyDictionary<string, object> properties,
        //     CancellationToken cancellationToken)
        // {
        //     if (properties.TryGetValue(WEBOCKET_PAYLOAD_AUTH_KEY, out object token) &&
        //         token is string stringToken)
        //     {
        //         context.Items[HTTP_CONTEXT_WEBSOCKET_AUTH_KEY] = stringToken;
        //         context.Features.Set<IAuthenticationFeature>(new AuthenticationFeature
        //         {
        //             OriginalPath = context.Request.Path,
        //             OriginalPathBase = context.Request.PathBase
        //         });
        //         // Give any IAuthenticationRequestHandler schemes a chance to handle the request
        //         var handlers = context.RequestServices.GetRequiredService<IAuthenticationHandlerProvider>();
        //         foreach (var scheme in await _schemes.GetRequestHandlerSchemesAsync())
        //         {
        //             var handler = handlers.GetHandlerAsync(context, scheme.Name) as IAuthenticationRequestHandler;
        //             if (handler != null && await handler.HandleRequestAsync())
        //             {
        //                 return ConnectionStatus.Reject();
        //             }
        //         }
        //         var defaultAuthenticate = await _schemes.GetDefaultAuthenticateSchemeAsync();
        //         if (defaultAuthenticate != null)
        //         {
        //             var result = await context.AuthenticateAsync(defaultAuthenticate.Name);
        //             if (result?.Principal != null)
        //             {
        //                 context.User = result.Principal;
        //                 return ConnectionStatus.Accept();
        //             }
        //         }
        //     }
        //     return ConnectionStatus.Reject();
        // }

        public async ValueTask <ConnectionStatus> OnConnectAsync(ISocketConnection connection,
                                                                 InitializeConnectionMessage message,
                                                                 CancellationToken cancellationToken)
        {
            var schemes = connection.RequestServices.GetService <IAuthenticationSchemeProvider>();

            if (schemes is null)
            {
                Console.WriteLine("Failed to get authentication scheme provider");
                return(ConnectionStatus.Reject());
            }

            if (message.Payload?[WEBOCKET_PAYLOAD_AUTH_KEY] is not string stringToken)
            {
                Console.WriteLine("authToken was missing from request");
                return(ConnectionStatus.Reject());
            }

            connection.HttpContext.Items[HTTP_CONTEXT_WEBSOCKET_AUTH_KEY] = stringToken;
            connection.HttpContext.Features.Set <IAuthenticationFeature>(new AuthenticationFeature
            {
                OriginalPath     = connection.HttpContext.Request.Path,
                OriginalPathBase = connection.HttpContext.Request.PathBase
            });
            // Give any IAuthenticationRequestHandler schemes a chance to handle the request
            var handlers = connection.HttpContext.RequestServices.GetRequiredService <IAuthenticationHandlerProvider>();

            foreach (var scheme in await schemes.GetRequestHandlerSchemesAsync())
            {
                var handler =
                    handlers.GetHandlerAsync(connection.HttpContext, scheme.Name) as IAuthenticationRequestHandler;
                if (handler != null && await handler.HandleRequestAsync())
                {
                    return(ConnectionStatus.Reject());
                }
            }

            var defaultAuthenticate = await schemes.GetDefaultAuthenticateSchemeAsync();

            if (defaultAuthenticate != null)
            {
                var result = await connection.HttpContext.AuthenticateAsync(defaultAuthenticate.Name);

                if (result?.Principal != null)
                {
                    connection.HttpContext.User = result.Principal;
                    return(ConnectionStatus.Accept());
                }
            }

            Console.WriteLine($"Failed to authenticate token {stringToken}");
            return(ConnectionStatus.Reject());
        }
예제 #3
0
        public Task <ConnectionStatus> OnReceiveAsync(
            ISocketConnection connection,
            InitializeConnectionMessage message,
            CancellationToken cancellationToken)
        {
            if (_interceptor != null &&
                connection is WebSocketConnection con)
            {
                return(_interceptor.OnOpenAsync(
                           con.HttpContext,
                           message.Payload,
                           cancellationToken));
            }

            return(Task.FromResult(ConnectionStatus.Accept()));
        }
        /// <summary>
        /// Intercepts the websocket connection, extracts the JWT from the onOpenMessage and authenticate the user with it. The connection will be rejected if the no JWT is given.
        /// </summary>
        public async Task <ConnectionStatus> OnOpenAsync(
            HttpContext context,
            IReadOnlyDictionary <string, object> properties,
            CancellationToken cancellationToken
            )
        {
            if (properties.TryGetValue(WEBOCKET_PAYLOAD_AUTH_KEY, out object token) &&
                token is string stringToken)
            {
                // Das Token dem HTTP Context hinzufügen, sodass dies später für über den TokenRetriever verwendet werden aknn
                context.Items[HTTP_CONTEXT_WEBSOCKET_AUTH_KEY] = stringToken;

                context.Features.Set <IAuthenticationFeature>(new AuthenticationFeature
                {
                    OriginalPath     = context.Request.Path,
                    OriginalPathBase = context.Request.PathBase
                });

                // Give any IAuthenticationRequestHandler schemes a chance to handle the request
                var handlers = context.RequestServices.GetRequiredService <IAuthenticationHandlerProvider>();
                foreach (var scheme in await _schemes.GetRequestHandlerSchemesAsync())
                {
                    var handler = handlers.GetHandlerAsync(context, scheme.Name) as IAuthenticationRequestHandler;
                    if (handler != null && await handler.HandleRequestAsync())
                    {
                        return(ConnectionStatus.Reject());
                    }
                }

                var defaultAuthenticate = await _schemes.GetDefaultAuthenticateSchemeAsync();

                if (defaultAuthenticate != null)
                {
                    // Benutzer mithilfe des Tokens authentifizieren
                    var result = await context.AuthenticateAsync(defaultAuthenticate.Name);

                    // war die Authentifizierung erfolgreich wird die Anfrage angenommen und der Websockt kann Nachrichten erhalten
                    if (result?.Principal != null)
                    {
                        context.User = result.Principal;
                        return(ConnectionStatus.Accept());
                    }
                }
            }
            // Sollte kein Token vorhanden sein, wird die Anfrage abgelehnt
            return(ConnectionStatus.Reject());
        }
        protected override async Task HandleAsync(
            ISocketConnection connection,
            InitializeConnectionMessage message,
            CancellationToken cancellationToken)
        {
            ConnectionStatus connectionStatus =
                _connectMessageInterceptor == null
                    ? ConnectionStatus.Accept()
                    : await _connectMessageInterceptor.OnReceiveAsync(
                    connection, message, cancellationToken)
                .ConfigureAwait(false);

            if (connectionStatus.Accepted)
            {
                await connection.SendAsync(
                    AcceptConnectionMessage.Default.Serialize(),
                    cancellationToken)
                .ConfigureAwait(false);

                await connection.SendAsync(
                    KeepConnectionAliveMessage.Default.Serialize(),
                    cancellationToken)
                .ConfigureAwait(false);
            }
            else
            {
                var rejectMessage = connectionStatus.Extensions == null
                    ? new RejectConnectionMessage(
                    connectionStatus.Message)
                    : new RejectConnectionMessage(
                    connectionStatus.Message,
                    connectionStatus.Extensions);

                await connection.SendAsync(
                    rejectMessage.Serialize(),
                    cancellationToken)
                .ConfigureAwait(false);

                // TODO : resources
                await connection.CloseAsync(
                    connectionStatus.Message,
                    SocketCloseStatus.PolicyViolation,
                    cancellationToken)
                .ConfigureAwait(false);
            }
        }
        public async ValueTask <ConnectionStatus> OnConnectAsync(
            ISocketConnection connection,
            InitializeConnectionMessage message,
            CancellationToken cancellationToken)
        {
            // Auth
            object?token   = null;
            var    payload = message.Payload ?? throw new Exception("Payload is missing. Can not authenticate user.");

            payload?.TryGetValue(WEBOCKET_PAYLOAD_AUTH_KEY, out token);

            if (token != null && token is string stringToken)
            {
                // Do auth
                var context = connection.HttpContext;

                context.Items.TryAdd(HTTP_CONTEXT_WEBSOCKET_AUTH_KEY, stringToken);
                context.Features.Set <IAuthenticationFeature>(new AuthenticationFeature
                {
                    OriginalPath     = context.Request.Path,
                    OriginalPathBase = context.Request.PathBase
                });


                var authResult = await context.AuthenticateAsync(IdentityServerAuthenticationDefaults.AuthenticationScheme);

                if (authResult?.Principal != null)
                {
                    context.User = authResult.Principal;
                    // add connection to manager
                    _webSocketManager.AddSocketConnection(connection);
                    return(ConnectionStatus.Accept());
                }
                else
                {
                    // reject websocket because user is not authenticated
                    return(ConnectionStatus.Reject());
                }
            }
            else
            {
                return(ConnectionStatus.Reject());
            }
        }
        public async Task <ConnectionStatus> OnOpenAsync(
            HttpContext context,
            IReadOnlyDictionary <string, object> properties,
            CancellationToken cancellationToken)
        {
            if (properties.TryGetValue(WEBOCKET_PAYLOAD_AUTH_KEY, out object token) &&
                token is string stringToken)
            {
                context.Items[HTTP_CONTEXT_WEBSOCKET_AUTH_KEY] = stringToken;
                context.Features.Set <IAuthenticationFeature>(new AuthenticationFeature
                {
                    OriginalPath     = context.Request.Path,
                    OriginalPathBase = context.Request.PathBase
                });
                // Give any IAuthenticationRequestHandler schemes a chance to handle the request
                var handlers = context.RequestServices.GetRequiredService <IAuthenticationHandlerProvider>();
                foreach (var scheme in await _schemes.GetRequestHandlerSchemesAsync())
                {
                    var handler = handlers.GetHandlerAsync(context, scheme.Name) as IAuthenticationRequestHandler;
                    if (handler != null && await handler.HandleRequestAsync())
                    {
                        return(ConnectionStatus.Reject());
                    }
                }
                var defaultAuthenticate = await _schemes.GetDefaultAuthenticateSchemeAsync();

                if (defaultAuthenticate != null)
                {
                    var result = await context.AuthenticateAsync(defaultAuthenticate.Name);

                    if (result?.Principal != null)
                    {
                        var webSocketContext = context.RequestServices.GetService <WebSocketContext>();
                        webSocketContext.User = result.Principal;
                        context.User          = result.Principal;
                        return(ConnectionStatus.Accept());
                    }
                }
            }
            return(ConnectionStatus.Reject());
        }
예제 #8
0
 public virtual ValueTask <ConnectionStatus> OnConnectAsync(
     ISocketConnection connection,
     InitializeConnectionMessage message,
     CancellationToken cancellationToken) =>
 new ValueTask <ConnectionStatus>(ConnectionStatus.Accept());
예제 #9
0
 public SocketSessionInterceptorMock(ConnectionStatus connectionStatus = null)
 {
     _connectionStatus = connectionStatus ?? ConnectionStatus.Accept();
 }