예제 #1
0
 public void AuthenticateClient(ICustomAuthPeer peer, IAuthenticateRequest authRequest, AuthSettings authSettings, SendParameters sendParameters, object state)
 {
     //TBD: why are we enqueuing could be done on the peers fiber
     this.fiber.Enqueue(() =>
                        this.OnAuthenticateClient(peer, authRequest, authSettings, sendParameters, state)
                        );
 }
        public virtual void OnCustomAuthenticationError(Photon.Common.ErrorCode errorCode, string debugMessage,
                                                        IAuthenticateRequest authenticateRequest, SendParameters sendParameters,
                                                        object state)
        {
            try
            {
                if (this.Connected == false)
                {
                    return;
                }

                if (log.IsDebugEnabled)
                {
                    log.DebugFormat("Client custom authentication failed: appId={0}, result={1}, msg={2}", authenticateRequest.ApplicationId, errorCode, debugMessage);
                }

                var operationResponse = new OperationResponse((byte)Hive.Operations.OperationCode.Authenticate)
                {
                    ReturnCode   = (short)errorCode,
                    DebugMessage = debugMessage,
                };

                this.SendOperationResponse(operationResponse, sendParameters);
                this.SetCurrentOperationHandler(OperationHandlerInitial.Instance);
            }
            catch (Exception ex)
            {
                log.Error(ex);
                var errorResponse = new OperationResponse((byte)Hive.Operations.OperationCode.Authenticate)
                {
                    ReturnCode = (short)Photon.Common.ErrorCode.InternalServerError
                };
                this.SendOperationResponse(errorResponse, sendParameters);
            }
        }
예제 #3
0
 public void AuthenticateClient(ICustomAuthPeer peer, IAuthenticateRequest authRequest, AuthSettings authSettings, SendParameters sendParameters, object state)
 {
     //TBD: why are we enqueuing could be done on the peers fiber
     this.fiber.Enqueue(() =>
         this.OnAuthenticateClient(peer, authRequest, authSettings, sendParameters, state)
     );
 }
 protected override void OnAuthenticateClient(
     ICustomAuthPeer peer, 
     IAuthenticateRequest authRequest, 
     AuthSettings authSettings,
     SendParameters sendParameters, object state)
 {
     base.OnAuthenticateClient(peer, authRequest, authSettings, sendParameters, state);
 }
예제 #5
0
 public AuthQueueState(ICustomAuthPeer peer, IAuthenticateRequest authenticateRequest,
                       SendParameters sendParameters, object state)
 {
     this.Peer = peer;
     this.AuthenticateRequest = authenticateRequest;
     this.State          = state;
     this.SendParameters = sendParameters;
 }
예제 #6
0
 /// <inheritdoc />
 public Task <IAuthenticateResponse> AuthenticateAsync(IAuthenticateRequest request,
                                                       CancellationToken cancellationToken = default(CancellationToken)
                                                       ) =>
 Dispatcher.DispatchAsync <IAuthenticateRequest, AuthenticateRequestParameters, AuthenticateResponse, IAuthenticateResponse>(
     request,
     cancellationToken,
     (p, d, c) => LowLevelDispatch.XpackSecurityAuthenticateDispatchAsync <AuthenticateResponse>(p, c)
     );
예제 #7
0
 public HmacAuthenticationHandler(IAuthenticateRequest authenticateRequest)
 {
     if (authenticateRequest == null)
     {
         throw new ArgumentNullException("authenticateRequest");
     }
     this.AuthenticateRequest = authenticateRequest;
 }
예제 #8
0
 /// <summary>
 /// Create a renewed Authentication Token on Master server - to be validated on GS
 /// </summary>
 /// <param name="userId"> </param>
 /// <param name="authRequest"></param>
 /// <returns></returns>
 public AuthenticationToken CreateAuthenticationToken(string userId, IAuthenticateRequest authRequest)
 {
     var token = new AuthenticationToken
                     {
                         ValidToTicks = DateTime.UtcNow.Add(this.ExpirationTime).Ticks,
                         UserId = userId,
                         AuthCookie = new Dictionary<string, object>(),
                         SessionId = Guid.NewGuid().ToString(),
                         Flags = authRequest.Flags,
                     };
     return token;
 }
예제 #9
0
        /// <summary>
        /// Create a renewed Authentication Token on Master server - to be validated on GS
        /// </summary>
        /// <param name="userId"> </param>
        /// <param name="authRequest"></param>
        /// <returns></returns>
        public AuthenticationToken CreateAuthenticationToken(string userId, IAuthenticateRequest authRequest)
        {
            var token = new AuthenticationToken
            {
                ValidToTicks = DateTime.UtcNow.Add(this.ExpirationTime).Ticks,
                UserId       = userId,
                AuthCookie   = new Dictionary <string, object>(),
                SessionId    = Guid.NewGuid().ToString(),
                Flags        = authRequest.Flags,
            };

            return(token);
        }
예제 #10
0
 public virtual AuthenticationToken CreateAuthenticationToken(IAuthenticateRequest authRequest, 
     AuthSettings authSettings, 
     string userId, 
     Dictionary<string, object> authCookie)
 {
     var token = new AuthenticationToken
                     {
                         UserId = userId,
                         AuthCookie = authCookie,
                         Flags = authRequest.Flags,
                     };
     this.SetupToken(token);
     return token;
 }
예제 #11
0
        public virtual AuthenticationToken CreateAuthenticationToken(IAuthenticateRequest authRequest,
                                                                     AuthSettings authSettings,
                                                                     string userId,
                                                                     Dictionary <string, object> authCookie)
        {
            var token = new AuthenticationToken
            {
                UserId     = userId,
                AuthCookie = authCookie,
                Flags      = authRequest.Flags,
            };

            this.SetupToken(token);
            return(token);
        }
        public override AuthenticationToken CreateAuthenticationToken(IAuthenticateRequest authRequest, AuthSettings authSettings, string userId, Dictionary <string, object> authCookie)
        {
            var authResult = (ApplicationAccount)authSettings;

            var token = this.CreateAuthenticationToken(authResult, authRequest, userId, authCookie);

            token.MaxCcu            = authResult.MaxCcu;
            token.IsCcuBurstAllowed = authResult.IsCcuBurstAllowed;
            token.PrivateCloud      = authResult.PrivateCloud;

            var authOnceRequest = authRequest as IAuthOnceRequest;

            if (authOnceRequest != null)
            {
                token.EncryptionData = EncryptionDataGenerator.Generate(authOnceRequest.EncryptionMode);
            }

            return(token);
        }
예제 #13
0
        public virtual AuthenticationToken CreateAuthenticationToken(IAuthenticateRequest authRequest, AuthSettings authSettings, string userId, Dictionary <string, object> authCookie)
        {
            var token = new AuthenticationToken
            {
                ApplicationId      = authRequest.ApplicationId,
                ApplicationVersion = authRequest.ApplicationVersion,
                UserId             = userId,
                AuthCookie         = authCookie,
                Flags = authRequest.Flags,
                CustomAuthProvider = authRequest.ClientAuthenticationType,
            };

            var authOnceRequest = authRequest as IAuthOnceRequest;

            if (authOnceRequest != null)
            {
                token.EncryptionData = EncryptionDataGenerator.Generate(authOnceRequest.EncryptionMode);
            }
            this.SetupToken(token);
            return(token);
        }
        private void RedirectPeerToNull(IAuthenticateRequest authRequest, SendParameters sendParameters)
        {
            var encryptionData = NullPayloadEncryptionData;

            if (this.authOnceUsed)
            {
                var authOnceRequest = (IAuthOnceRequest)authRequest;
                if (authOnceRequest.EncryptionMode == (byte)EncryptionModes.DatagramEncyption)
                {
                    encryptionData = NullDatagrammEncryptionData;
                }
                else
                {
                    encryptionData = NullDatagrammWithRIEncryptionData;
                }
            }

            var masterEndPoint = this.LocalIPAddressIsIPv6 ? Settings.Default.IPv6NullAddress : Settings.Default.IPv4NullAddress;

            masterEndPoint += ":5055";//we may use any port

            var authResponse = new AuthenticateResponse
            {
                MasterEndpoint      = masterEndPoint,
                AuthenticationToken = NullStringToken,
                UserId         = NullUserId,
                EncryptionData = encryptionData,
                Cluster        = NullCluster,
            };

            var operation         = (Operation)authRequest;
            var operationResponse = new OperationResponse(operation.OperationRequest.OperationCode, authResponse)
            {
                ReturnCode = 0
            };

            this.SendOperationResponse(operationResponse, sendParameters);
        }
        protected virtual void DoCustomAuthenticationError(ErrorCode errorCode, string debugMessage, IAuthenticateRequest authenticateRequest, SendParameters sendParameters)
        {
            try
            {
                if (log.IsDebugEnabled)
                {
                    log.DebugFormat(
                        "DoCustomAuthenticationError: appId={0}, errorCode={1}, debugMessage={2}", authenticateRequest.ApplicationId, errorCode, debugMessage);
                }

                if (!this.Connected)
                {
                    return;
                }

                var errorResponse = new OperationResponse(GetAuthOpCode(this.authOnceUsed))
                {
                    ReturnCode = (short)errorCode, DebugMessage = debugMessage
                };
                this.SendOperationResponse(errorResponse, sendParameters);
            }
            catch (Exception ex)
            {
                log.Error(ex);

                var errorResponse = new OperationResponse(GetAuthOpCode(this.authOnceUsed))
                {
                    ReturnCode = (short)ErrorCode.InternalServerError
                };
                this.SendOperationResponse(errorResponse, sendParameters);
            }

            this.ScheduleDisconnect(this.GetDisconnectTime());
        }
        public static void CheckEncryptedToken(AuthTokenFactory tokenFactory, LogCountGuard appCheckGuard, object authToken, IAuthenticateRequest authenticateRequest,
                                               ApplicationAccount applicationAccount, bool useV1Token)
        {
            var strToken = authToken as string;

            if (string.IsNullOrEmpty(strToken))
            {
                return;
            }

            AuthenticationToken token;
            string errorMsg;

            if (useV1Token)
            {
                if (!tokenFactory.DecryptAuthenticationTokenV1(strToken, out token, out errorMsg))
                {
                    log.WarnFormat(appCheckGuard, "AppId Check: Failed to decrypt just created V1 token. errorMsg:{3}, AppId:{0}/{1}, token:{2}",
                                   authenticateRequest.ApplicationId, authenticateRequest.ApplicationVersion, authToken, errorMsg);
                    return;
                }
            }
            else
            {
                if (!tokenFactory.DecryptAuthenticationTokenV2(strToken, out token, out errorMsg))
                {
                    log.WarnFormat(appCheckGuard,
                                   "AppId Check: Failed to decrypt just created V2 token. ErrorMsg:{3}, AppId:{0}/{1}, token:{2}",
                                   authenticateRequest.ApplicationId, authenticateRequest.ApplicationVersion, authToken, errorMsg);
                    return;
                }
            }

            Guid guid;

            if (!Guid.TryParse(token.ApplicationId, out guid))
            {
                log.WarnFormat(appCheckGuard,
                               "AppId Check: Wrong appId in token after encryption. appId:{0}, account appId:{1}, request appId:{2}, token:{0}",
                               token.ApplicationId, applicationAccount.ApplicationId, authenticateRequest.ApplicationId, authToken);
            }
        }
예제 #17
0
        public virtual void OnCustomAuthenticationError(Photon.Common.ErrorCode errorCode, string debugMessage,
                                                      IAuthenticateRequest authenticateRequest, SendParameters sendParameters,
                                                      object state)
        {
            try
            {
                if (this.Connected == false)
                {
                    return;
                }

                if (log.IsDebugEnabled)
                {
                    log.DebugFormat("Client custom authentication failed: appId={0}, result={1}, msg={2}", authenticateRequest.ApplicationId, errorCode, debugMessage);
                }

                var operationResponse = new OperationResponse((byte)Hive.Operations.OperationCode.Authenticate)
                {
                    ReturnCode = (short)errorCode,
                    DebugMessage = debugMessage,
                };

                this.SendOperationResponse(operationResponse, sendParameters);
                this.SetCurrentOperationHandler(OperationHandlerInitial.Instance);
            }
            catch(Exception ex)
            {
                log.Error(ex);
                var errorResponse = new OperationResponse((byte)Hive.Operations.OperationCode.Authenticate) { ReturnCode = (short)Photon.Common.ErrorCode.InternalServerError };
                this.SendOperationResponse(errorResponse, sendParameters);
            }
        }
예제 #18
0
 public AuthQueueState(ICustomAuthPeer peer, IAuthenticateRequest authenticateRequest, 
     SendParameters sendParameters, object state)
 {
     this.Peer = peer;
     this.AuthenticateRequest = authenticateRequest;
     this.State = state;
     this.SendParameters = sendParameters;
 }
        protected override void HandleCustomAuthenticateResult(CustomAuthenticationResult customAuthResult, IAuthenticateRequest authenticateRequest, SendParameters sendParameters, AuthSettings authSettings)
        {
            var appAccount = (ApplicationAccount)authSettings;
            // try to get the master server instance for the specified application id
            CloudPhotonEndpointInfo masterServer;
            string message;

            if (
                !((PhotonCloudApp)this.application).CloudCache.TryGetPhotonEndpoint(
                    authenticateRequest,
                    appAccount,
                    out masterServer,
                    out message))
            {
                if (log.IsDebugEnabled)
                {
                    log.DebugFormat(
                        "MasterServer not found for region {0} on cloud {1} / service type {2}: {3}",
                        authenticateRequest.Region,
                        appAccount.PrivateCloud,
                        appAccount.ServiceType,
                        message);
                }

                var errorResponse = new OperationResponse(GetAuthOpCode(this.authOnceUsed))
                {
                    ReturnCode   = (short)ErrorCode.InvalidRegion,
                    DebugMessage = string.Format("No connections allowed on region {0}.", authenticateRequest.Region)
                };

                this.SendOperationResponse(errorResponse, sendParameters);
                this.ScheduleDisconnect(this.GetDisconnectTime());
                return;
            }

            // TODO: V2: check if the master server is connected.
            // if (masterServer.IsOnline == false)
            // {
            // var opResponse = new OperationResponse { OperationCode = (byte)OperationCode.Authenticate, ReturnCode = (int)AuthenticationErrorCode.ApplicationOffline };
            // this.SendOperationResponse(opResponse, sendParameters);
            // return;
            // }

            var endpointProtocol = this.authOnceUsed
                ? (NetworkProtocolType)((Photon.NameServer.Operations.AuthOnceRequest)authenticateRequest).Protocol
                : this.NetworkProtocol;

            var masterEndPoint = masterServer.GetEndPoint(endpointProtocol, this.LocalPort,
                                                          isIPv6: this.LocalIPAddressIsIPv6, useHostnames: this.IsIPv6ToIPv4Bridged);

            if (masterEndPoint == null)
            {
                if (log.IsDebugEnabled)
                {
                    log.DebugFormat("Master server endpoint for protocol {0} not found for master server {1}.", endpointProtocol, masterServer);
                }

                var errorResponse = new OperationResponse(GetAuthOpCode(this.authOnceUsed))
                {
                    ReturnCode   = (short)AuthErrorCode.ProtocolNotSupported,
                    DebugMessage = ErrorMessages.ProtocolNotSupported
                };

                this.SendOperationResponse(errorResponse, sendParameters);
                this.ScheduleDisconnect(this.GetDisconnectTime());
                return;
            }

            string userid;

            // the userid can be set
            if (!string.IsNullOrEmpty(customAuthResult.UserId))
            {
                // by authentication service <<< overides client
                userid = customAuthResult.UserId;
            }
            else if (!string.IsNullOrEmpty(authenticateRequest.UserId))
            {
                // or through the client
                userid = authenticateRequest.UserId;
            }
            else
            {
                // we generate a userid
                userid = Guid.NewGuid().ToString();
            }

            // create auth token
            var unencryptedToken = this.application.TokenCreator.CreateAuthenticationToken(
                authenticateRequest, appAccount, userid, customAuthResult.AuthCookie);

            if (customAuthResult.ExpireAt.HasValue)
            {
                unencryptedToken.ExpireAtTicks = (UnixStart + TimeSpan.FromSeconds(customAuthResult.ExpireAt.Value)).Ticks;
            }
            else if (authenticateRequest.ClientAuthenticationType == (byte)ClientAuthenticationType.Xbox)
            {
                log.Debug(xboxCustomAuthLogGuard, "Custom auth response for XBox does not contain ExpireAt");
            }

            var authToken = this.GetEncryptedAuthToken(unencryptedToken, masterServer);

            this.CheckEncryptedToken(authToken, authenticateRequest, appAccount, masterServer);

            var authResponse = new AuthenticateResponse
            {
                MasterEndpoint      = masterEndPoint,
                AuthenticationToken = authToken,
                Data           = customAuthResult.Data,
                Nickname       = customAuthResult.Nickname,
                UserId         = userid,
                EncryptionData = this.authOnceUsed ? GetEncryptionData(unencryptedToken) : null,
                Cluster        = masterServer.Cluster
            };

            var operationResponse = new OperationResponse(GetAuthOpCode(this.authOnceUsed), authResponse);

            this.SendOperationResponse(operationResponse, sendParameters);
        }
        protected override void DoCustomAuthenticationError(ErrorCode errorCode, string debugMessage, IAuthenticateRequest authenticateRequest, SendParameters sendParameters)
        {
            var opReq = (Operation)authenticateRequest;

            try
            {
                if (log.IsDebugEnabled)
                {
                    log.DebugFormat(
                        "DoCustomAuthenticationError: appId={0}, errorCode={1}, debugMessage={2}", authenticateRequest.ApplicationId, errorCode, debugMessage);
                }

                if (!this.Connected)
                {
                    return;
                }

                if (errorCode == ErrorCode.CustomAuthenticationOverload)
                {
                    this.RedirectPeerToNull(authenticateRequest, sendParameters);
                }
                else
                {
                    var errorResponse = new OperationResponse(opReq.OperationRequest.OperationCode)
                    {
                        ReturnCode = (short)errorCode, DebugMessage = debugMessage
                    };
                    this.SendOperationResponse(errorResponse, sendParameters);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);

                var errorResponse = new OperationResponse(opReq.OperationRequest.OperationCode)
                {
                    ReturnCode = (short)ErrorCode.InternalServerError
                };
                this.SendOperationResponse(errorResponse, sendParameters);
            }

            this.ScheduleDisconnect(this.GetDisconnectTime());
        }
 public virtual void OnCustomAuthenticationError(ErrorCode errorCode, string debugMessage, IAuthenticateRequest authenticateRequest, SendParameters sendParameters)
 {
     this.RequestFiber.Enqueue(() => this.DoCustomAuthenticationError(errorCode, debugMessage, authenticateRequest, sendParameters));
 }
		/// <inheritdoc/>
		public Task<IAuthenticateResponse> AuthenticateAsync(IAuthenticateRequest request) =>
			this.Dispatcher.DispatchAsync<IAuthenticateRequest, AuthenticateRequestParameters, AuthenticateResponse, IAuthenticateResponse>(
				request,
				(p,d ) => this.LowLevelDispatch.XpackSecurityAuthenticateDispatchAsync<AuthenticateResponse>(p)
			);
예제 #23
0
        public bool TryGetPhotonEndpoint(IAuthenticateRequest request, ApplicationAccount appAccount, out CloudPhotonEndpointInfo result, out string message)
        {
            result  = null;
            message = null;

            if (string.IsNullOrEmpty(appAccount.PrivateCloud))
            {
                message = string.Format("No private cloud set for applicaton ID {0} - can not get Master", request.ApplicationId);
                log.Error(message);
                return(false);
            }

            if (string.IsNullOrEmpty(request.Region))
            {
                message = string.Format("No region set in authenticate request for application ID {0} - can not determine Master", request.ApplicationId);
                log.Error(message);
                return(false);
            }

            var privateCloud    = appAccount.PrivateCloud;
            var requestedRegion = request.Region.ToLower();

            var cluster = DefaultClusterName;

            // if a cluster "*" has been passed then we return a random cluster
            // if an actual value has been passed we try to return that particular cluster
            if (requestedRegion.Contains("/"))
            {
                var regionArray = requestedRegion.Split(RegionSeparators, StringSplitOptions.RemoveEmptyEntries);
                if (regionArray.Length > 0)
                {
                    requestedRegion = regionArray[0];
                }

                // if account is enterprise account, we allow to select cluster using auth request
                if (regionArray.Length > 1 && appAccount.IsEnterprise)
                {
                    cluster = regionArray[1];
                }
            }

            var defaultAppCluster = DefaultClusterName;

            // app is cluster0 app and there is cluster0 in requested region then we set cluster0
            if (appAccount.IsAppForCluster0 &&
                this.cluster0Presence.TryGetValue(MakeCluster0IndexKey(appAccount, requestedRegion), out bool present) &&
                present)
            {
                defaultAppCluster = Cluster0Name;
                cluster           = Cluster0Name;
            }

            if (appAccount.RegionClusterInfos != null && appAccount.RegionClusterInfos.ContainsKey(requestedRegion))
            {
                var clusters = appAccount.RegionClusterInfos[requestedRegion];

                // if "*" has been passed we just chose a random one:
                if (RandomClusterName.Equals(cluster))
                {
                    cluster = clusters[rnd.Next(0, clusters.Count)];
                }
                else
                {
                    // check if a valid cluster has been found:
                    if (!clusters.Contains(cluster))
                    {
                        if (!clusters.Contains(defaultAppCluster))
                        {
                            cluster = clusters[0];
                        }
                        else
                        {
                            cluster = defaultAppCluster;
                        }
                    }
                }
            }

            //enterprise customer who send "*" and cluster was not replaced with value from RegionClusterInfos (because info is not set)
            if (RandomClusterName.Equals(cluster) && appAccount.IsEnterprise)
            {
                cluster = DefaultClusterName;
            }

            result = this.TryGetPhotonEndpoint(privateCloud, requestedRegion, cluster, appAccount.ServiceType);

            if (log.IsDebugEnabled)
            {
                if (result == null)
                {
                    log.Debug("No endpoint found");
                }
                else
                {
                    log.DebugFormat("Endpoint found 2 - Hostname {0}, UDP: {1}, HTTP: {2}", result.UdpHostname, result.UdpEndPoint, result.HttpEndPoint);
                }
            }

            return(result != null);
        }
예제 #24
0
        public virtual string CreateEncryptedAuthenticationToken(IAuthenticateRequest authRequest, AuthSettings authSettings, string userId, Dictionary <string, object> customParameter)
        {
            var token = this.CreateAuthenticationToken(authRequest, authSettings, userId, customParameter);

            return(this.EncryptAuthenticationToken(token, false));
        }
예제 #25
0
 public virtual string CreateEncryptedAuthenticationToken(IAuthenticateRequest authRequest, AuthSettings authSettings, string userId, Dictionary<string, object> customParameter)
 {
     var token = this.CreateAuthenticationToken(authRequest, authSettings, userId, customParameter);
     return this.EncryptAuthenticationToken(token, false);
 }
예제 #26
0
        protected virtual void OnAuthenticateClient(ICustomAuthPeer peer, IAuthenticateRequest authRequest, AuthSettings authSettings, SendParameters sendParameters, object state)
        {
            try
            {
                if (log.IsDebugEnabled)
                {
                    log.DebugFormat("Authenticating client {0} - custom authentication type: {1}",
                         peer.ConnectionId,
                         authRequest.ClientAuthenticationType);
                }

                // when authentication data is provided check if
                // it is either a byte array or string and convert to byte array
                // if it's a string value
                byte[] authData = null;
                if (authRequest.ClientAuthenticationData != null)
                {
                    authData = authRequest.ClientAuthenticationData as byte[];
                    if (authData == null)
                    {
                        var stringData = authRequest.ClientAuthenticationData as string;
                        if (stringData == null)
                        {
                            peer.OnCustomAuthenticationError(
                                ErrorCode.CustomAuthenticationFailed,
                                "Authentication data type not supported",
                                authRequest,
                                sendParameters,
                                state);

                            this.IncrementFailedCustomAuth();
                            return;
                        }

                        authData = Encoding.UTF8.GetBytes(stringData);
                    }
                }

                if (string.IsNullOrEmpty(authRequest.ClientAuthenticationParams) && authData == null && this.isAnonymousAccessAllowed)
                {
                    // instant callback - treat as anonymous user:
                    if (log.IsDebugEnabled)
                    {
                        log.DebugFormat("Authenticate client: grant access as anonymous user: conId={0}", peer.ConnectionId);
                    }

                    var customResult = new CustomAuthenticationResult { ResultCode = CustomAuthenticationResultCode.Ok };
                    peer.OnCustomAuthenticationResult(customResult, authRequest, sendParameters, state);
                    return;
                }

                // take auth type from auth request (default: custom)
                var authenticationType = (ClientAuthenticationType)authRequest.ClientAuthenticationType;

                ClientAuthenticationQueue authQueue;
                if (this.authenticationServices.TryGetValue(authenticationType, out authQueue) == false)
                {
                    if (log.IsWarnEnabled)
                    {
                        log.WarnFormat("Authentication type not supported: {0} for AppId={1}/{2}", authenticationType,
                            authRequest.ApplicationId, authRequest.ApplicationVersion);
                    }

                    peer.OnCustomAuthenticationError(
                        ErrorCode.CustomAuthenticationFailed,
                        "Authentication type not supported",
                        authRequest,
                        sendParameters,
                        state);
                    this.IncrementFailedCustomAuth();
                    return;
                }

                var queueState = new AuthQueueState(peer, authRequest, sendParameters, state);
                authQueue.EnqueueRequest(authRequest.ClientAuthenticationParams, authData, this.AuthQueueResponseCallback, queueState);
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }
예제 #27
0
        protected virtual void OnAuthenticateClient(ICustomAuthPeer peer, IAuthenticateRequest authRequest, AuthSettings authSettings, SendParameters sendParameters, object state)
        {
            try
            {
                if (log.IsDebugEnabled)
                {
                    log.DebugFormat("Authenticating client {0} - custom authentication type: {1}",
                                    peer.ConnectionId,
                                    authRequest.ClientAuthenticationType);
                }

                // when authentication data is provided check if
                // it is either a byte array or string and convert to byte array
                // if it's a string value
                byte[] authData = null;
                if (authRequest.ClientAuthenticationData != null)
                {
                    authData = authRequest.ClientAuthenticationData as byte[];
                    if (authData == null)
                    {
                        var stringData = authRequest.ClientAuthenticationData as string;
                        if (stringData == null)
                        {
                            peer.OnCustomAuthenticationError(
                                ErrorCode.CustomAuthenticationFailed,
                                "Authentication data type not supported",
                                authRequest,
                                sendParameters,
                                state);

                            this.IncrementFailedCustomAuth();
                            return;
                        }

                        authData = Encoding.UTF8.GetBytes(stringData);
                    }
                }

                if (string.IsNullOrEmpty(authRequest.ClientAuthenticationParams) && authData == null && this.isAnonymousAccessAllowed)
                {
                    // instant callback - treat as anonymous user:
                    if (log.IsDebugEnabled)
                    {
                        log.DebugFormat("Authenticate client: grant access as anonymous user: conId={0}", peer.ConnectionId);
                    }

                    var customResult = new CustomAuthenticationResult {
                        ResultCode = CustomAuthenticationResultCode.Ok
                    };
                    peer.OnCustomAuthenticationResult(customResult, authRequest, sendParameters, state);
                    return;
                }

                // take auth type from auth request (default: custom)
                var authenticationType = (ClientAuthenticationType)authRequest.ClientAuthenticationType;

                ClientAuthenticationQueue authQueue;
                if (this.authenticationServices.TryGetValue(authenticationType, out authQueue) == false)
                {
                    if (log.IsWarnEnabled)
                    {
                        log.WarnFormat("Authentication type not supported: {0} for AppId={1}/{2}", authenticationType,
                                       authRequest.ApplicationId, authRequest.ApplicationVersion);
                    }

                    peer.OnCustomAuthenticationError(
                        ErrorCode.CustomAuthenticationFailed,
                        "Authentication type not supported",
                        authRequest,
                        sendParameters,
                        state);
                    this.IncrementFailedCustomAuth();
                    return;
                }

                var queueState = new AuthQueueState(peer, authRequest, sendParameters, state);
                authQueue.EnqueueRequest(authRequest.ClientAuthenticationParams, authData, this.AuthQueueResponseCallback, queueState);
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }
        protected virtual void OnAuthenticateClient(ICustomAuthPeer peer, IAuthenticateRequest authRequest, AuthSettings authSettings, SendParameters sendParameters, object state)
        {
            try
            {
                if (log.IsDebugEnabled)
                {
                    log.DebugFormat("Authenticating client {0} - custom authentication type: {1}",
                                    peer.ConnectionId,
                                    authRequest.ClientAuthenticationType);
                }

                // when authentication data is provided check if
                // it is either a byte array or string and convert to byte array
                // if it's a string value
                byte[] authData = null;
                if (authRequest.ClientAuthenticationData != null)
                {
                    authData = authRequest.ClientAuthenticationData as byte[];
                    if (authData == null)
                    {
                        var stringData = authRequest.ClientAuthenticationData as string;
                        if (stringData == null)
                        {
                            peer.OnCustomAuthenticationError(
                                ErrorCode.CustomAuthenticationFailed,
                                "Authentication data type not supported",
                                authRequest,
                                sendParameters,
                                state);

                            this.IncrementFailedCustomAuth();
                            return;
                        }

                        authData = Encoding.UTF8.GetBytes(stringData);
                    }
                }

                //Test auth custom
                bool teste = true;

                if (teste)
                {
                    string authpar = authRequest.ClientAuthenticationParams;


                    log.Debug("Douglas teste authpar :: CustomAuthHandler.cs :: authpar :: ");


                    object  parms = sendParameters;
                    JObject o     = (JObject)JToken.FromObject(parms);
                    foreach (var item in o)
                    {
                        log.Debug("Douglas teste sendParameters :: CustomAuthHandler.cs :: item.Key [" + item.Key + "] item.Value[" + item.Value + "]");
                    }

                    log.Debug("Douglas teste ok :: CustomAuthHandler.cs");
                    var customResult = new CustomAuthenticationResult {
                        ResultCode = CustomAuthenticationResultCode.Ok
                    };
                    peer.OnCustomAuthenticationResult(customResult, authRequest, sendParameters, state);
                    return;
                }
                else
                {
                    log.Debug("Douglas teste erro :: CustomAuthHandler.cs");
                    peer.OnCustomAuthenticationError(
                        ErrorCode.CustomAuthenticationFailed,
                        "Authentication failed.",
                        authRequest,
                        sendParameters,
                        state);

                    this.IncrementFailedCustomAuth();
                    return;
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }

            /* Alterado para testes
             * try
             * {
             *  if (log.IsDebugEnabled)
             *  {
             *      log.DebugFormat("Authenticating client {0} - custom authentication type: {1}",
             *           peer.ConnectionId,
             *           authRequest.ClientAuthenticationType);
             *  }
             *
             *  // when authentication data is provided check if
             *  // it is either a byte array or string and convert to byte array
             *  // if it's a string value
             *  byte[] authData = null;
             *  if (authRequest.ClientAuthenticationData != null)
             *  {
             *      authData = authRequest.ClientAuthenticationData as byte[];
             *      if (authData == null)
             *      {
             *          var stringData = authRequest.ClientAuthenticationData as string;
             *          if (stringData == null)
             *          {
             *              peer.OnCustomAuthenticationError(
             *                  ErrorCode.CustomAuthenticationFailed,
             *                  "Authentication data type not supported",
             *                  authRequest,
             *                  sendParameters,
             *                  state);
             *
             *              this.IncrementFailedCustomAuth();
             *              return;
             *          }
             *
             *          authData = Encoding.UTF8.GetBytes(stringData);
             *      }
             *  }
             *
             *  if (string.IsNullOrEmpty(authRequest.ClientAuthenticationParams) && authData == null && this.isAnonymousAccessAllowed)
             *  {
             *      // instant callback - treat as anonymous user:
             *      if (log.IsDebugEnabled)
             *      {
             *          log.DebugFormat("Authenticate client: grant access as anonymous user: conId={0}", peer.ConnectionId);
             *      }
             *
             *      var customResult = new CustomAuthenticationResult { ResultCode = CustomAuthenticationResultCode.Ok };
             *      peer.OnCustomAuthenticationResult(customResult, authRequest, sendParameters, state);
             *      return;
             *  }
             *
             *  // take auth type from auth request (default: custom)
             *  var authenticationType = (ClientAuthenticationType)authRequest.ClientAuthenticationType;
             *
             *  ClientAuthenticationQueue authQueue;
             *  if (this.authenticationServices.TryGetValue(authenticationType, out authQueue) == false)
             *  {
             *      if (log.IsWarnEnabled)
             *      {
             *          log.WarnFormat("Authentication type not supported: {0} for AppId={1}/{2}", authenticationType,
             *              authRequest.ApplicationId, authRequest.ApplicationVersion);
             *      }
             *
             *      peer.OnCustomAuthenticationError(
             *          ErrorCode.CustomAuthenticationFailed,
             *          "Authentication type not supported",
             *          authRequest,
             *          sendParameters,
             *          state);
             *      this.IncrementFailedCustomAuth();
             *      return;
             *  }
             *
             *  var queueState = new AuthQueueState(peer, authRequest, sendParameters, state);
             *  authQueue.EnqueueRequest(authRequest.ClientAuthenticationParams, authData, this.AuthQueueResponseCallback, queueState);
             * }
             * catch (Exception ex)
             * {
             *  log.Error(ex);
             * }
             */
        }
        protected virtual void DoCustomAuthenticationResult(CustomAuthenticationResult customAuthResult, IAuthenticateRequest authenticateRequest, SendParameters sendParameters, AuthSettings authSettings)
        {
            if (customAuthResult == null)
            {
                log.WarnFormat("Custom authentication error. customAuthResult is null. appId={0}/{1}",
                               authenticateRequest.ApplicationId, authenticateRequest.ApplicationVersion);
                return;
            }

            try
            {
                if (log.IsDebugEnabled)
                {
                    log.DebugFormat(
                        "DoCustomAuthenticationResult: appId={0}, resultCode={1}, message={2}, client connected:{3}",
                        authenticateRequest.ApplicationId,
                        customAuthResult.ResultCode,
                        customAuthResult.Message,
                        this.Connected);
                }

                if (!this.Connected)
                {
                    return;
                }

                OperationResponse operationResponse;

                switch (customAuthResult.ResultCode)
                {
                default:
                    operationResponse = new OperationResponse(GetAuthOpCode(this.authOnceUsed))
                    {
                        ReturnCode   = (short)ErrorCode.CustomAuthenticationFailed,
                        DebugMessage = customAuthResult.Message
                    };
                    this.SendOperationResponse(operationResponse, new SendParameters());
                    return;

                case CustomAuthenticationResultCode.Data:
                    var auth = new AuthenticateResponse {
                        Data = customAuthResult.Data
                    };
                    operationResponse = new OperationResponse(GetAuthOpCode(this.authOnceUsed), auth);
                    this.SendOperationResponse(operationResponse, sendParameters);
                    return;

                case CustomAuthenticationResultCode.Ok:
                    this.HandleCustomAuthenticateResult(customAuthResult, authenticateRequest, sendParameters, authSettings);
                    return;
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                var errorResponse = new OperationResponse(GetAuthOpCode(this.authOnceUsed))
                {
                    ReturnCode   = (short)ErrorCode.InternalServerError,
                    DebugMessage = ex.Message,
                };
                this.SendOperationResponse(errorResponse, sendParameters);
            }
        }
        protected virtual void HandleCustomAuthenticateResult(CustomAuthenticationResult customAuthResult, IAuthenticateRequest authenticateRequest, SendParameters sendParameters, AuthSettings authSettings)
        {
            //try to get the master server instance for the specified application id


            PhotonEndpointInfo masterServer;
            string             message;

            if (!this.application.ServerCache.TryGetPhotonEndpoint(authenticateRequest.Region, out masterServer, out message))
            {
                if (log.IsDebugEnabled)
                {
                    log.DebugFormat(
                        "MasterServer not found for service type {2}: {3}",
                        authenticateRequest.Region,
                        message);
                }

                var errorResponse = new OperationResponse(GetAuthOpCode(this.authOnceUsed))
                {
                    ReturnCode   = (short)ErrorCode.InvalidRegion,
                    DebugMessage = string.Format("No connections allowed on region {0}.", authenticateRequest.Region)
                };

                this.SendOperationResponse(errorResponse, sendParameters);
                return;
            }

            var    nameServerAuthRequest = (AuthenticateRequest)authenticateRequest;
            var    isAuthOnceUsed        = nameServerAuthRequest.OperationRequest.OperationCode != (byte)OperationCode.Authenticate;
            var    endpointProtocol      = isAuthOnceUsed ? (NetworkProtocolType)((AuthOnceRequest)nameServerAuthRequest).Protocol : this.NetworkProtocol;
            string masterEndPoint;

            //tmp webrtc
            try
            {
                masterEndPoint = masterServer.GetEndPoint(endpointProtocol, this.LocalPort,
                                                          isIPv6: this.LocalIPAddressIsIPv6, useHostnames: this.IsIPv6ToIPv4Bridged);
            }
            catch (Exception e)
            {
                masterEndPoint = masterServer.GetEndPoint(endpointProtocol, 0);

                var str = string.Format(
                    "Custom Auth: Exception during GetEndPoint call. EndPoint protocol:{0}, LocalPort:{1}, isIpV6:{2}, useHostNames:{3}",
                    endpointProtocol, this.LocalPort, this.LocalIPAddressIsIPv6, this.IsIPv6ToIPv4Bridged);

                log.Warn(exceptionGuard, str, e);
            }

            if (masterEndPoint == null)
            {
                if (log.IsDebugEnabled)
                {
                    log.DebugFormat("Master server endpoint for protocol {0} not found for master server {1}.", this.NetworkProtocol, masterServer);
                }

                var errorResponse = new OperationResponse(GetAuthOpCode(this.authOnceUsed))
                {
                    ReturnCode   = (short)AuthErrorCode.ProtocolNotSupported,
                    DebugMessage = ErrorMessages.ProtocolNotSupported
                };

                this.SendOperationResponse(errorResponse, sendParameters);
                return;
            }

            string userid;

            // the userid can be set
            if (!string.IsNullOrEmpty(customAuthResult.UserId))
            {
                // by authentication service <<< overides client
                userid = customAuthResult.UserId;
            }
            else if (!string.IsNullOrEmpty(authenticateRequest.UserId))
            {
                // or through the client
                userid = authenticateRequest.UserId;
            }
            else
            {
                // we generate a userid
                userid = Guid.NewGuid().ToString();
            }

            // create auth token
            var unencryptedToken = this.application.TokenCreator.CreateAuthenticationToken(
                authenticateRequest, new AuthSettings(), userid, customAuthResult.AuthCookie);

            var authToken = this.GetEncryptedAuthToken(unencryptedToken);

            var authResponse = new AuthenticateResponse
            {
                MasterEndpoint      = masterEndPoint,
                AuthenticationToken = authToken,
                Data           = customAuthResult.Data,
                Nickname       = customAuthResult.Nickname,
                UserId         = userid,
                EncryptionData = GetEncryptionData(unencryptedToken),
            };

            var operationResponse = new OperationResponse(GetAuthOpCode(this.authOnceUsed), authResponse);

            this.SendOperationResponse(operationResponse, sendParameters);
        }
예제 #31
0
        public virtual string CreateEncryptedAuthenticationToken(IAuthenticateRequest authRequest, AuthSettings authSettings, string userId)
        {
            var token = this.CreateAuthenticationToken(authRequest, authSettings, userId, null);

            return(this.EncryptAuthenticationToken(token, false));
        }
 private void CheckEncryptedToken(object authToken, IAuthenticateRequest authenticateRequest, ApplicationAccount applicationAccount, CloudPhotonEndpointInfo master)
 {
     VAppsAuthTokenFactory.CheckEncryptedToken(this.application.TokenCreator, appCheckGuard, authToken,
                                               authenticateRequest, applicationAccount, master.UseV1Token);
 }
예제 #33
0
 /// <summary>
 /// Create a renewed Authentication Token on Master server - to be validated on GS
 /// </summary>
 /// <param name="userId"> </param>
 /// <param name="authRequest"></param>
 /// <returns></returns>
 public AuthenticationToken CreateAuthenticationToken(string userId, IAuthenticateRequest authRequest)
 {
     return(this.CreateAuthenticationToken(authRequest, null, userId, new Dictionary <string, object>()));
 }
        public virtual void OnCustomAuthenticationResult(CustomAuthenticationResult customAuthResult, IAuthenticateRequest authenticateRequest,
                                                         SendParameters sendParameters, object state)
        {
            var authRequest  = (AuthenticateRequest)authenticateRequest;
            var authSettings = (AuthSettings)state;

            this.RequestFiber.Enqueue(() => this.DoCustomAuthenticationResult(customAuthResult, authRequest, sendParameters, authSettings));
        }
예제 #35
0
 public virtual void OnCustomAuthenticationResult(CustomAuthenticationResult customAuthResult, IAuthenticateRequest authenticateRequest,
                                          SendParameters sendParameters, object state)
 {
     var authRequest = (AuthenticateRequest)authenticateRequest;
     var authSettings = (AuthSettings)state;
     this.RequestFiber.Enqueue(() => this.DoCustomAuthenticationResult(customAuthResult, authRequest, sendParameters, authSettings));
 }
예제 #36
0
 /// <inheritdoc />
 public AuthenticateResponse Authenticate(IAuthenticateRequest request) =>
 DoRequest <IAuthenticateRequest, AuthenticateResponse>(request, request.RequestParameters);
예제 #37
0
 public override void OnCustomAuthenticationResult(CustomAuthenticationResult customAuthResult, IAuthenticateRequest authenticateRequest,
     SendParameters sendParameters, object state)
 {
     base.OnCustomAuthenticationResult(customAuthResult, authenticateRequest, sendParameters, state);
 }
예제 #38
0
 public virtual string CreateEncryptedAuthenticationToken(IAuthenticateRequest authRequest, AuthSettings authSettings, string userId)
 {
     var token = this.CreateAuthenticationToken(authRequest, authSettings, userId, null);
     return this.EncryptAuthenticationToken(token, false);
 }
예제 #39
0
 /// <inheritdoc />
 public Task <AuthenticateResponse> AuthenticateAsync(IAuthenticateRequest request, CancellationToken ct = default) =>
 DoRequestAsync <IAuthenticateRequest, AuthenticateResponse>(request, request.RequestParameters, ct);
예제 #40
0
 /// <inheritdoc />
 public IAuthenticateResponse Authenticate(IAuthenticateRequest request) =>
 Dispatcher.Dispatch <IAuthenticateRequest, AuthenticateRequestParameters, AuthenticateResponse>(
     request,
     (p, d) => LowLevelDispatch.XpackSecurityAuthenticateDispatch <AuthenticateResponse>(p)
     );
        /// <summary>
        /// Create a renewed Authentication Token on Master server - to be validated on GS
        /// </summary>
        /// <returns></returns>
        private VAppsAuthenticationToken CreateAuthenticationToken(ApplicationAccount account, IAuthenticateRequest authRequest,
                                                                   string userId, Dictionary <string, object> authCookie = null)
        {
            var token = new VAppsAuthenticationToken
            {
                ApplicationId      = account.ApplicationId,
                ApplicationVersion = authRequest.ApplicationVersion,
                MaxCcu             = int.MaxValue,
                IsCcuBurstAllowed  = true,
                UserId             = userId,
                PrivateCloud       = null,
                AuthCookie         = new Dictionary <string, object>(),
                HasExternalApi     = account.HasExternalApi,
                Flags = authRequest.Flags,
                CustomAuthProvider = authRequest.ClientAuthenticationType,
            };

            this.SetupToken(token);
            if (authCookie != null)
            {
                token.AuthCookie = authCookie;
            }
            return(token);
        }
		/// <inheritdoc/>
		public IAuthenticateResponse Authenticate(IAuthenticateRequest request) =>
			this.Dispatcher.Dispatch<IAuthenticateRequest, AuthenticateRequestParameters, AuthenticateResponse>(
				request,
				(p, d) =>this.LowLevelDispatch.XpackSecurityAuthenticateDispatch<AuthenticateResponse>(p)
			);
 public static Task <AuthenticateResponse> AuthenticateAsync(this IElasticClient client, IAuthenticateRequest request,
                                                             CancellationToken ct = default
                                                             )
 => client.Security.AuthenticateAsync(request, ct);