Beispiel #1
0
        internal void Initialise()
        {
            SetAuthMethod();

            CurrentAuthOptions = Options;
            CurrentTokenParams = Options.DefaultTokenParams;
            if (CurrentTokenParams != null)
            {
                CurrentTokenParams.ClientId = Options.GetClientId(); //Ensure the correct ClientId is set in AblyAuth
            }
            if (AuthMethod == AuthMethod.Basic)
            {
                LogCurrentAuthenticationMethod();
                return;
            }

            Logger.Debug("Using token authentication.");
            if (Options.TokenDetails != null)
            {
                CurrentToken = Options.TokenDetails;
            }
            else if (Options.Token.IsNotEmpty())
            {
                CurrentToken = new TokenDetails(Options.Token);
            }
            LogCurrentAuthenticationMethod();
        }
Beispiel #2
0
        public static bool IsValidToken(this TokenDetails token)
        {
            if (token == null)
            {
                return(false);
            }
            var exp = token.Expires;

            return((exp == DateTimeOffset.MinValue) || (exp >= token.Now()));
        }
Beispiel #3
0
        public static bool IsValidToken(this TokenDetails token, DateTimeOffset now)
        {
            if (token == null)
            {
                return(false);
            }

            if (token.Expires == DateTimeOffset.MinValue)
            {
                return(true);
            }

            return(!token.IsExpired(now));
        }
Beispiel #4
0
        /// <summary>
        /// Checks whether the token is valid.
        /// </summary>
        /// <param name="token"><see cref="TokenDetails"/>.</param>
        /// <param name="serverTime">the server time instance of now to compare with the token.</param>
        /// <returns>true / false.</returns>
        public static bool IsValidToken(this TokenDetails token, DateTimeOffset?serverTime)
        {
            if (token == null)
            {
                return(false);
            }

            // (RSA4b1) We can only check validity of the token if it is a full TokenDetails object
            // and we already have the server time
            if (serverTime is null || token.CanBeUsedToCheckExpiry == false)
            {
                return(true);
            }

            return(token.IsExpired(serverTime.Value) == false);
        }
Beispiel #5
0
        /// <summary>
        /// Makes a token request. This will make a token request now, even if the library already
        /// has a valid token. It would typically be used to issue tokens for use by other clients.
        /// </summary>
        /// <param name="tokenParams">The <see cref="TokenRequest"/> data used for the token</param>
        /// <param name="options">Extra <see cref="AuthOptions"/> used for creating a token </param>
        /// <returns>A valid ably token</returns>
        /// <exception cref="AblyException"></exception>
        public virtual async Task <TokenDetails> RequestTokenAsync(TokenParams tokenParams = null, AuthOptions options = null)
        {
            var mergedOptions = options != null?options.Merge(Options) : Options;

            string keyId = "", keyValue = "";

            if (mergedOptions.Key.IsNotEmpty())
            {
                var key = mergedOptions.ParseKey();
                keyId    = key.KeyName;
                keyValue = key.KeySecret;
            }

            var @params = MergeTokenParamsWithDefaults(tokenParams);

            if (mergedOptions.QueryTime.GetValueOrDefault(false))
            {
                @params.Timestamp = await _rest.TimeAsync();
            }

            EnsureSecureConnection();

            var request = _rest.CreatePostRequest($"/keys/{keyId}/requestToken");

            request.SkipAuthentication = true;
            TokenRequest postData = null;

            if (mergedOptions.AuthCallback != null)
            {
                var callbackResult = await mergedOptions.AuthCallback(@params);

                if (callbackResult == null)
                {
                    throw new AblyException("AuthCallback returned null");
                }

                if (callbackResult is TokenDetails)
                {
                    return(callbackResult as TokenDetails);
                }

                if (callbackResult is TokenRequest)
                {
                    postData = callbackResult as TokenRequest;

                    request.Url = $"/keys/{postData.KeyName}/requestToken";
                }
                else
                {
                    throw new AblyException($"AuthCallback returned an unsupported type ({callbackResult.GetType()}. Expected either TokenDetails or TokenRequest");
                }
            }
            else if (mergedOptions.AuthUrl.IsNotEmpty())
            {
                var response = await CallAuthUrl(mergedOptions, @params);

                if (response.Type == ResponseType.Text) //Return token string
                {
                    return(new TokenDetails(response.TextResponse));
                }

                var signedData = response.TextResponse;
                var jData      = JObject.Parse(signedData);

                if (TokenDetails.IsToken(jData))
                {
                    return(JsonHelper.DeserializeObject <TokenDetails>(jData));
                }

                postData = JsonHelper.Deserialize <TokenRequest>(signedData);

                request.Url = $"/keys/{postData.KeyName}/requestToken";
            }
            else
            {
                if (keyId.IsEmpty() || keyValue.IsEmpty())
                {
                    throw new AblyException("TokenAuth is on but there is no way to generate one");
                }

                postData = new TokenRequest().Populate(@params, keyId, keyValue);
            }

            request.PostData = postData;

            TokenDetails result = await _rest.ExecuteRequest <TokenDetails>(request);

            if (result == null)
            {
                throw new AblyException(new ErrorInfo("Invalid token response returned", 500));
            }

            return(result);
        }
Beispiel #6
0
        /// <summary>
        /// Makes a token request. This will make a token request now, even if the library already
        /// has a valid token. It would typically be used to issue tokens for use by other clients.
        /// </summary>
        /// <param name="tokenParams">The <see cref="TokenRequest"/> data used for the token</param>
        /// <param name="authOptions">Extra <see cref="AuthOptions"/> used for creating a token </param>
        /// <returns>A valid ably token</returns>
        /// <exception cref="AblyException"></exception>
        public virtual async Task <TokenDetails> RequestTokenAsync(TokenParams tokenParams = null, AuthOptions authOptions = null)
        {
            EnsureSecureConnection();

            // (RSA8e)
            authOptions = authOptions ?? CurrentAuthOptions ?? Options ?? new AuthOptions();
            tokenParams = tokenParams ?? CurrentTokenParams ?? TokenParams.WithDefaultsApplied();

            string keyId = string.Empty, keyValue = string.Empty;

            if (authOptions.Key.IsNotEmpty())
            {
                var key = authOptions.ParseKey();
                keyId    = key.KeyName;
                keyValue = key.KeySecret;
            }

            if (tokenParams.ClientId.IsEmpty())
            {
                tokenParams.ClientId = ClientId;
            }

            await SetTokenParamsTimestamp(authOptions, tokenParams);

            var request = _rest.CreatePostRequest($"/keys/{keyId}/requestToken");

            request.SkipAuthentication = true;
            TokenRequest postData = null;

            if (authOptions.AuthCallback != null)
            {
                bool shouldCatch = true;
                try
                {
                    var callbackResult = await authOptions.AuthCallback(tokenParams);

                    if (callbackResult == null)
                    {
                        throw new AblyException("AuthCallback returned null", 80019);
                    }

                    if (callbackResult is TokenDetails)
                    {
                        return(callbackResult as TokenDetails);
                    }

                    if (callbackResult is TokenRequest || callbackResult is string)
                    {
                        postData    = GetTokenRequest(callbackResult);
                        request.Url = $"/keys/{postData.KeyName}/requestToken";
                    }
                    else
                    {
                        shouldCatch = false;
                        throw new AblyException($"AuthCallback returned an unsupported type ({callbackResult.GetType()}. Expected either TokenDetails or TokenRequest", 80019, HttpStatusCode.BadRequest);
                    }
                }
                catch (Exception ex) when(shouldCatch)
                {
                    var statusCode = HttpStatusCode.Unauthorized;

                    if (ex is AblyException aex)
                    {
                        statusCode = aex.ErrorInfo.StatusCode == HttpStatusCode.Forbidden
                            ? HttpStatusCode.Forbidden
                            : HttpStatusCode.Unauthorized;
                    }

                    throw new AblyException(
                              new ErrorInfo(
                                  "Error calling AuthCallback, token request failed. See inner exception for details.",
                                  80019,
                                  statusCode), ex);
                }
            }
            else if (authOptions.AuthUrl.IsNotEmpty())
            {
                var responseText = String.Empty;
                try
                {
                    var response = await CallAuthUrl(authOptions, tokenParams);

                    if (response.Type == ResponseType.Text || response.Type == ResponseType.Jwt)
                    {
                        // RSC8c:
                        // The token retrieved is assumed by the library to be a token string
                        // if the response has Content-Type "text/plain" or "application/jwt"
                        return(new TokenDetails(response.TextResponse, Now));
                    }

                    responseText = response.TextResponse;
                    var jData = JObject.Parse(responseText);

                    if (TokenDetails.IsToken(jData))
                    {
                        return(JsonHelper.DeserializeObject <TokenDetails>(jData));
                    }

                    postData = JsonHelper.Deserialize <TokenRequest>(responseText);

                    request.Url = $"/keys/{postData.KeyName}/requestToken";
                }
                catch (AblyException ex)
                {
                    throw new AblyException(
                              new ErrorInfo(
                                  "Error calling Auth URL, token request failed. See the InnerException property for details of the underlying exception.",
                                  80019,
                                  ex.ErrorInfo.StatusCode == HttpStatusCode.Forbidden
                                ? ex.ErrorInfo.StatusCode
                                : HttpStatusCode.Unauthorized,
                                  ex),
                              ex);
                }
                catch (Exception ex)
                {
                    string reason =
                        "Error handling Auth URL, token request failed. See the InnerException property for details of the underlying exception.";

                    if (ex is JsonReaderException)
                    {
                        reason =
                            $"Error parsing JSON response '{responseText}' from Auth URL.See the InnerException property for details of the underlying exception.";
                    }

                    throw new AblyException(
                              new ErrorInfo(
                                  reason,
                                  80019,
                                  HttpStatusCode.InternalServerError,
                                  ex),
                              ex);
                }
            }
            else
            {
                if (keyId.IsEmpty() || keyValue.IsEmpty())
                {
                    throw new AblyException("TokenAuth is on but there is no way to generate one", 80019);
                }

                postData = new TokenRequest(Now).Populate(tokenParams, keyId, keyValue);
            }

            request.PostData = postData;

            TokenDetails result = await _rest.ExecuteRequest <TokenDetails>(request);

            if (result == null)
            {
                throw new AblyException("Invalid token response returned", 80019);
            }

            //TODO: Very ugly stuff
            result.Now = Now;

            return(result);
        }
 public AblyAuthUpdatedEventArgs(TokenDetails token)
     : this()
 {
     Token = token;
 }
Beispiel #8
0
 private bool Equals(TokenDetails other)
 {
     return(string.Equals(Token, other.Token) && Expires.Equals(other.Expires) && Issued.Equals(other.Issued) && Equals(Capability, other.Capability) && string.Equals(ClientId, other.ClientId));
 }
Beispiel #9
0
 public static bool IsExpired(this TokenDetails token, DateTimeOffset now)
 {
     return(token.Expires < now);
 }