Exemplo n.º 1
0
        private void OnlineRequest_Finished(string responce)
        {
            _appLicenseJwt = JsonConvert.DeserializeObject <AppLicenseJwt>(responce);
            var payload = JwtUtilities.GetPayload(_appLicenseJwt.Token);

            _appLicense = CreateAndSaveLicenses(payload);
        }
        public void IsIShareCompliant_HeaderHasNoAlg_ReturnsFalse()
        {
            var now        = DateTime.UtcNow;
            var jwtContent =
                $@"{{
                    ""typ"": ""JWT"",
                    ""x5c"": [""{ Constants.AbcParty.PublicKeyBase64Der }""]
                }}
                .
                {{
                    ""iss"": ""{Constants.SchemeOwner.ClientId}"",
                    ""sub"": ""{Constants.SchemeOwner.ClientId}"",
                    ""aud"": ""{Constants.AbcParty.ClientId}"",
                    ""jti"": ""{Guid.NewGuid()}"",
                    ""exp"": ""{JwtUtilities.DateTimeToEpoch(now.AddSeconds(30))}"",
                    ""iat"": ""{JwtUtilities.DateTimeToEpoch(now)}""
                }}";
            var jwtToken       = JwtUtilities.SignJwt(jwtContent, Constants.AbcParty.PrivateKey);
            var assertionModel = CreateValidAssertionModel(jwtToken);
            var args           = new TokenValidationArgs(
                assertionModel,
                Constants.SchemeOwner.ClientId,
                Constants.AbcParty.ClientId);

            var result = _sut.IsIShareCompliant(args);

            result.Should().BeFalse();
        }
Exemplo n.º 3
0
 public HttpResponseMessage RefreshToken()
 {
     try
     {
         var token = JwtUtilities.FetchFromHeader(ActionContext);
         return(Request.CreateResponse(HttpStatusCode.Accepted,
                                       JwtUtilities.RefreshToken(token, ConfigurationManager.AppSettings["Jwtsecret"])));
     }
     catch (Exception e)
     {
         return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e));
     }
 }
Exemplo n.º 4
0
        public HttpResponseMessage TestToken()
        {
            try
            {
                var exp = JwtUtilities.GetExpireTime(Request);
                var x   = new
                {
                    status   = true,
                    validFor = (exp - DateTime.UtcNow).TotalSeconds
                };

                return(Request.CreateResponse(HttpStatusCode.OK, x));
            }
            catch (Exception e)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e));
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// License check finished, check response and either load locally or validate.
        /// </summary>
        /// <param name="request">The http request.</param>
        /// <param name="response">The http response for the request.</param>
        private void OnlineRequest_Finished(WebRequest /*HTTPRequest*/ request, WebResponse /*HTTPResponse*/ response)
        {
            var res = (HttpWebResponse)response;

            try
            {
                if (res.StatusCode == HttpStatusCode.GatewayTimeout || response == null)
                //if (request.State == HTTPRequestStates.ConnectionTimedOut || response == null)
                {
                    //Debug.LogWarning("LicenseManager: No response.");
                    //_errorMessage = string.Format(TimeOutMessage, response?.StatusCode);
                    _errorMessage = string.Format(TimeOutMessage, res?.StatusCode);
                }
                else
                {
                    if (res.StatusCode != HttpStatusCode.OK)
                    //if (response.StatusCode != ValidResponseCode)
                    {
                        //Debug.LogWarning("LicenseManager: Invalid status code returned - " + response.StatusCode);
                        //_errorMessage = string.Format(InvalidResponseMessage, response?.StatusCode);
                        _errorMessage = string.Format(InvalidResponseMessage, res?.StatusCode);
                    }
                    else
                    {
                        //_appLicenseJwt = JsonConvert.DeserializeObject<AppLicenseJwt>(response.DataAsText);
                        var          stream = response.GetResponseStream();
                        StreamReader reader = new StreamReader(stream);
                        string       data   = reader.ReadToEnd();
                        _appLicenseJwt = JsonConvert.DeserializeObject <AppLicenseJwt>(data);
                        var payload = JwtUtilities.GetPayload(_appLicenseJwt.Token);
                        _appLicense = CreateAndSaveLicenses(payload);
                    }
                }
            }
            catch (Exception e)
            {
                //Debug.LogWarning("Exception while processing license response: " + e);
                _errorMessage = string.Format(InvalidResponseMessage, "error while processing response");
            }

            var validLicense = CheckLocalLicense();
        }
Exemplo n.º 6
0
        /// <summary>
        /// Tries to deserialize the license from local storage and to convert it from jwt.
        /// </summary>
        private void LoadLocalLicense()
        {
            _licenseFileUri = Path.Combine(PathHelper.GetApplicationWorkingDirectory(), FileName);

            if (!File.Exists(_licenseFileUri /*.OriginalUri*/))
            {
                return;
            }

            using (var stream = new FileStream(_licenseFileUri, FileMode.OpenOrCreate) /*_resourceManager.GetStream(_licenseFileUri)*/)
            {
                if (stream != null)
                {
                    var reader        = new StreamReader(stream);
                    var localFileText = reader.ReadToEnd();
                    _appLicenseJwt = JsonConvert.DeserializeObject <AppLicenseJwt>(localFileText);
                    var payload = JwtUtilities.GetPayload(_appLicenseJwt.Token);
                    _appLicense = JsonConvert.DeserializeObject <AppLicense>(payload);
                }
            }
        }
        public void IsIShareCompliant_HeaderAlgNeqRS256_ReturnsFalse()
        {
            var signingAlgorithm = JwtUtilities.CreateSigningCredentials(
                Constants.AbcParty.PrivateKey,
                SecurityAlgorithms.RsaSsaPssSha512);
            var jwtSecurityToken = JwtUtilities.CreateToken(
                Constants.SchemeOwner.ClientId,
                Constants.AbcParty.ClientId,
                Constants.AbcParty.PublicKeyBase64Der,
                signingAlgorithm);
            var jwtToken       = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
            var assertionModel = CreateValidAssertionModel(jwtToken);
            var args           = new TokenValidationArgs(
                assertionModel,
                Constants.SchemeOwner.ClientId,
                Constants.AbcParty.ClientId);

            var result = _sut.IsIShareCompliant(args);

            result.Should().BeFalse("Only RS256 should be supported.");
        }
Exemplo n.º 8
0
        /// <summary>
        /// Checks if a local license file is available and if it's still valid.
        /// Does check both the jwt signature and the actual license validity and expiration.
        /// </summary>
        /// <returns><c>true</c> if a valid license is found, otherwise <c>false</c>.</returns>
        private bool CheckLocalLicense()
        {
            if (string.IsNullOrEmpty(_appLicense?.Until) || string.IsNullOrEmpty(_appLicenseJwt?.Token))
            {
                return(false);
            }

            var verifiedSignature = JwtUtilities.VerifySignature(_appLicenseJwt.Token, PubKeyText, HashAlgorithm);

            if (!verifiedSignature)
            {
                return(false);
            }

            var validUntilString = _appLicense.Until;
            var isUtc            = false;

            if (validUntilString.Contains(UtcIdentifier))
            {
                validUntilString = validUntilString.Replace(UtcIdentifier, string.Empty);
                isUtc            = true;
            }

            var validUntil = DateTime.ParseExact(validUntilString, DateFormat, CultureInfo.InvariantCulture);

            if (isUtc)
            {
                validUntil = validUntil.ToUniversalTime();
            }

            var currentTime = DateTime.Now;

            if (DateTime.Compare(currentTime, validUntil) > 0)
            {
                //Debug.LogWarning("License expired: " + validUntil);
                return(false);
            }

            return(_appLicense.Licensed);
        }
Exemplo n.º 9
0
        public HttpResponseMessage GetToken([FromBody] string clientKey)
        {
            try
            {
                if (clientKey != ConfigurationManager.AppSettings["clientKey"])
                {
                    throw new Exception("Key does not match");
                }

                var claims = new Dictionary <string, string>
                {
                    { "clientKey", clientKey },
                    { "exp", DateTimeOffset.Now.AddMinutes(5).ToUnixTimeSeconds().ToString() }
                };
                return(Request.CreateResponse(HttpStatusCode.Accepted,
                                              JwtUtilities.GenerateToken(claims, ConfigurationManager.AppSettings["Jwtsecret"])));
            }
            catch (Exception e)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e));
            }
        }
 private static string CreateJwtString() =>
 JwtUtilities.Create(
     Constants.SchemeOwner.ClientId,
     Constants.AbcParty.ClientId,
     Constants.AbcParty.PrivateKey,
     Constants.AbcParty.PublicKeyBase64Der);