Ejemplo n.º 1
0
        public void ShouldAddGrant()
        {
            var token     = new AccessToken("AC456", "SK123", "foobar");
            var delta     = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            var timestamp = (int)Math.Floor(delta.TotalSeconds);

            token.AddGrant(new ConversationsGrant());

            var encoded = token.ToJWT();

            Assert.IsNotNull(encoded);
            Assert.IsNotEmpty(encoded);

            var decoded = JsonWebToken.Decode(encoded, "foobar");

            Assert.IsNotEmpty(decoded);
            var serializer = new JavaScriptSerializer();
            var payload    = (Dictionary <string, object>)serializer.DeserializeObject(decoded);

            Assert.IsNotNull(payload);

            Assert.AreEqual("SK123", payload["iss"]);
            Assert.AreEqual("AC456", payload["sub"]);
            var exp = Convert.ToInt64(payload["exp"]);

            Assert.AreEqual(timestamp + 3600, exp);
            var jti = (string)payload["jti"];

            Assert.AreEqual("SK123-" + timestamp.ToString(), jti);

            var grants = (Dictionary <string, object>)payload["grants"];

            Assert.AreEqual(1, grants.Count);
            Assert.IsNotNull(grants["rtc"]);
        }
Ejemplo n.º 2
0
        public object Login(string password, string user)
        {
            try
            {
                var result = CouchbaseStorageHelper.Instance.Get("profile::" + user, "default");
                if (result.Success && result.Status == Couchbase.IO.ResponseStatus.Success && result.Exception == null && result.Value != null)
                {
                    var jsonDecodedTokenString =
                        JsonWebToken
                        .Decode(result.Value, CouchbaseConfigHelper.Instance.JWTTokenSecret, false);

                    var jwtToken = JsonConvert.DeserializeAnonymousType(jsonDecodedTokenString, new { user = "", iat = "" });

                    if (jwtToken.iat == password)
                    {
                        return(new { success = result.Value });
                    }
                }
            }
            catch (Exception)
            {
                // Silence the Exception
            }

            return(new { success = false });
        }
Ejemplo n.º 3
0
    public static List <MechanicJsonData> LoadMechanicsRemote()
    {
        WebClient webClient = new WebClient();

        webClient.Headers.Add(HttpRequestHeader.Authorization, NetService.AuthHeader);
        string  downloadedString = webClient.DownloadString(NetService.FullUrl(NetService.kBalanceMechanicUrl));
        string  json             = JsonWebToken.Decode(downloadedString, NetService.secretKey);
        JObject parent           = JObject.Parse(json);
        JToken  arr = parent["response"]["data"];

        List <MechanicJsonData> mechanics = new List <MechanicJsonData>();
        int planetId = 0;

        foreach (JToken token in arr)
        {
            int    priceForFirstMechanic = token.Value <int>(0);
            int    priceIncreasing       = token.Value <int>(1);
            int    unitCountService      = token.Value <int>(2);
            float  fatigue = token.Value <float>(3);
            int    restoredPer10Seconds = token.Value <int>(4);
            double cashPrice            = token.Value <double>(5);
            mechanics.Add(new MechanicJsonData {
                planetId = planetId,
                fatigueUnitsPercentPerHour     = fatigue,
                priceForFirstMechanic          = priceForFirstMechanic,
                priceIncreasingForNextMechanic = priceIncreasing,
                serviceCashPrice = cashPrice,
                serviceUnitsRestoredPer10Seconds = restoredPer10Seconds,
                unitCountService = unitCountService
            });
            planetId++;
        }
        return(mechanics);
    }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request["token"] == null)
            {
                return;
            }

            var jwtToken = Request["token"];

            var payload = JsonWebToken.DecodeToObject(jwtToken, "", false) as IDictionary <string, object>;

            if (payload != null)
            {
                var usuario = new ManterUsuario().ObterUsuarioPorID((int)payload["id"]);

                try
                {
                    if (usuario != null && usuario.TrilhaTokenExpiry > DateTime.Now)
                    {
                        JsonWebToken.Decode(jwtToken, usuario.TrilhaToken);

                        var nivel = new ManterTrilhaNivel().ObterTrilhaNivelPorID((int)payload["nid"]);

                        if (!nivel.UsuarioPossuiMatricula((int)payload["id"]))
                        {
                            return;
                        }

                        var matricula = new ManterUsuarioTrilha().ObterPorUsuarioNivel(usuario.ID, nivel.ID);

                        if (matricula == null)
                        {
                            return;
                        }

                        MatriculaSessao = matricula;

                        new ManterUsuario().AdicionarTempoTokenTrilha(usuario);

                        ltrNomeNivel.Text = matricula.TrilhaNivel.Nome;

                        rptLojas.DataSource =
                            matricula.TrilhaNivel.ListaPontoSebrae
                            .Where(
                                x =>
                                x.ListaMissoes.SelectMany(m => m.ListaItemTrilha).Any(
                                    it =>
                                    it.Usuario == null &&
                                    it.ObterStatusParticipacoesItemTrilha(matricula) ==
                                    enumStatusParticipacaoItemTrilha.Aprovado));

                        rptLojas.DataBind();
                    }
                }
                catch
                {
                    throw;
                }
            }
        }
Ejemplo n.º 5
0
        public static void DeleteExpiredSessions(string secret)
        {
            var sessions = Directory.GetFiles(_sessionDirectory);

            foreach (string session in sessions)
            {
                System.IO.StreamReader file = new System.IO.StreamReader(session);
                string token = file.ReadLine();
                if (token != null)
                {
                    var json = JsonWebToken.Decode(token, secret, false);
                    NameValueCollection values = Json.Serialize(json);
                    var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                    var now       = Math.Round((DateTime.Now - unixEpoch).TotalSeconds);
                    if (long.Parse(values["exp"]) < now)
                    {
                        file.Dispose();
                        File.Delete(session);
                    }
                }
                else
                {
                    file.Dispose();
                    File.Delete(session);
                }
                file.Dispose();
            }
        }
Ejemplo n.º 6
0
        public void Should_be_able_to_get_JWT_from_LoginHandler()
        {
            var uri      = @"http://*****:*****@"{ ""email"": ""*****@*****.**"", ""password"": ""my_passw0rd!"" }";

            using (var client = new WebClient()) {
                client.Headers [HttpRequestHeader.ContentType] = "application/json";
                client.Headers [HttpRequestHeader.Accept]      = "application/json";

                try {
                    var result = client.UploadString(uri, postData);

                    Console.WriteLine("login result: '{0}'", result);

                    var jwtToken = jsonSerializer.Deserialize <JwtToken> (result);

                    Console.WriteLine("Token: '{0}'", jwtToken.Token);

                    var claimsJson = JsonWebToken.Decode(jwtToken.Token, new byte[0], false);

                    Console.WriteLine("Payload: '{0}'", claimsJson);
                }
                catch (WebException e) {
                    using (var reader = new StreamReader(e.Response.GetResponseStream())) {
                        Console.WriteLine(reader.ReadToEnd());
                    }
                    throw;
                }
            }
        }
Ejemplo n.º 7
0
    public static List <SecretaryJsonData> GetSecretariesRemote()
    {
        WebClient webClient = new WebClient();

        webClient.Headers.Add(HttpRequestHeader.Authorization, NetService.AuthHeader);
        string  downloadedString = webClient.DownloadString(NetService.FullUrl(NetService.kSecretaryBalanceUrl));
        string  json             = JsonWebToken.Decode(downloadedString, NetService.secretKey);
        JObject parent           = JObject.Parse(json);
        JToken  arr = parent["response"]["data"];

        List <SecretaryJsonData> secretaries = new List <SecretaryJsonData>();
        int planetId = 0;

        foreach (JToken token in arr)
        {
            int    priceForFirst           = token.Value <int>(0);
            int    priceIncreasing         = token.Value <int>(1);
            int    reportCountPerSecretary = token.Value <int>(2);
            float  fatigue = token.Value <float>(3);
            int    reportCountProcessedPer10Seconds = token.Value <int>(4);
            double cashPrice = token.Value <double>(5);
            secretaries.Add(new SecretaryJsonData {
                planetId = planetId,
                priceForFirstSecretary           = priceForFirst,
                priceIncreasingForNextSecretary  = priceIncreasing,
                reportCountPerSecretary          = reportCountPerSecretary,
                fatigueOfEfficiency              = fatigue,
                reportCountProcessedPer10Seconds = reportCountProcessedPer10Seconds,
                auditCashPrice = cashPrice
            });
            planetId++;
        }
        return(secretaries);
    }
Ejemplo n.º 8
0
    private static void DownloadManagers()
    {
        var       items     = JsonConvert.DeserializeObject <List <ManagerJsonData> >(Resources.Load <TextAsset>("Data/manager").text);
        WebClient webClient = new WebClient();

        webClient.Headers.Add(HttpRequestHeader.Authorization, NetService.AuthHeader);
        string downloadedString = webClient.DownloadString(NetService.FullUrl("http://bos.heatherglade.com/_dev/get_managers_prices"));
        string json             = JsonWebToken.Decode(downloadedString, NetService.secretKey);
        var    obj      = JObject.Parse(json);
        var    managers = obj["response"]["data"];
        var    index    = 0;

        foreach (var manager in managers)
        {
            double baseCost = manager[0].ToString().ToDouble();
            double coef     = manager[1].ToString().ToDouble();
            var    item     = GetWithId(items, index);
            index++;
            item.baseCost = baseCost;
            item.coef     = coef;
            Debug.Log($"manager => {index} loaded");
        }

        string         serializePath = Path.Combine(Application.dataPath, "Resources/Data/manager.json");
        JsonSerializer serializer    = new JsonSerializer();

        serializer.Formatting = Formatting.Indented;
        Serialize(serializePath, items);
        Debug.Log("managerss saved...".Colored(ConsoleTextColor.orange).BoldItalic());
        EditorUtility.DisplayDialog("Managers loaded", $"data saved to {"Resources/Data/manager.json"}", "Ok");
    }
Ejemplo n.º 9
0
    private static List <BankLevelJsonData> GetBankLevelDataList()
    {
        WebClient webClient = new WebClient();

        webClient.Headers.Add(HttpRequestHeader.Authorization, NetService.AuthHeader);
        string  downloadedString = webClient.DownloadString(NetService.FullUrl(NetService.kBankUrl));
        string  json             = JsonWebToken.Decode(downloadedString, NetService.secretKey);
        JObject parent           = JObject.Parse(json);
        JToken  arr = parent["response"]["data"];

        List <BankLevelJsonData> bankLevels = new List <BankLevelJsonData>();
        int level = 1;

        foreach (JToken token in arr)
        {
            int               price    = token.Value <int>(0);
            float             profit   = token.Value <float>(1);
            float             interval = token.Value <float>(2);
            BankLevelJsonData data     = new BankLevelJsonData {
                level           = level,
                levelPriceCoins = price,
                profit          = profit,
                profitInterval  = interval
            };
            level++;
            bankLevels.Add(data);
        }
        return(bankLevels);
    }
Ejemplo n.º 10
0
    private static void DownloadTransportStrength()
    {
        WebClient webClient = new WebClient();

        webClient.Headers.Add(HttpRequestHeader.Authorization, NetService.AuthHeader);
        string  downloadedString = webClient.DownloadString(NetService.FullUrl(NetService.kTransportStrengthUrl));
        string  json             = JsonWebToken.Decode(downloadedString, NetService.secretKey);
        JObject parent           = JObject.Parse(json);
        JToken  arr = parent["response"]["data"];

        int generatorId = 0;
        List <UnitStrengthJsonData> strengths = new List <UnitStrengthJsonData>();

        foreach (JToken token in arr)
        {
            float strength = token.Value <float>();
            strengths.Add(new UnitStrengthJsonData {
                id       = generatorId,
                strength = strength
            });
            generatorId++;
        }

        string         serializePath = Path.Combine(Application.dataPath, "Resources/Data/strengths.json");
        JsonSerializer serializer    = new JsonSerializer();

        serializer.Formatting = Formatting.Indented;
        Serialize(serializePath, strengths);
        Debug.Log("strengths saved...");
        EditorUtility.DisplayDialog("Strengths loaded", $"data saved to {"Resources/Data/strengths.json"}", "Ok");
    }
Ejemplo n.º 11
0
        /// <summary>
        /// Checks if the token is valid
        /// </summary>
        /// <returns></returns>
        private bool IsTokenValid()
        {
            try
            {
                if (IsAuthenticated()) //If token is found in cookie
                {
                    //check expiry date
                    var jsonSerializer = new JavaScriptSerializer();
                    var payloadJson    = JsonWebToken.Decode(Utils.GetCookie("lc_token"), "token");

                    var payloadData = jsonSerializer.Deserialize <Dictionary <string, object> >(payloadJson);
                    payloadData.TryGetValue("exp", out object expiration);
                    var validTo = FromUnixTime(long.Parse(expiration.ToString()));
                    if (DateTime.Compare(validTo, DateTime.UtcNow) <= 0)
                    {
                        return(false);
                    }
                    return(true);
                }
                return(false);
            }
            catch (NullReferenceException)
            {
                return(false);
            }
        }
Ejemplo n.º 12
0
    private static void DownloadManagerImprovements()
    {
        WebClient webClient = new WebClient();

        webClient.Headers.Add(HttpRequestHeader.Authorization, NetService.AuthHeader);
        string  downloadedString = webClient.DownloadString(NetService.FullUrl(NetService.kManagerImprovements));
        string  json             = JsonWebToken.Decode(downloadedString, NetService.secretKey);
        JObject parent           = JObject.Parse(json);
        JToken  arr = parent["response"]["data"];

        var efficiencyImrpovements      = NetService.ParseManagerEfficiencyImprovements(arr);
        var rollbackImprovements        = NetService.ParseManagerRollbackImprovements(arr);
        var megaImprovement             = NetService.ParseMegaManagerImprovement(arr);
        ManagerImproveJsonData jsonData = new ManagerImproveJsonData {
            efficiencyImprovements = efficiencyImrpovements,
            rollbackImprovements   = rollbackImprovements,
            megaImprovement        = megaImprovement
        };

        string         serializePath = Path.Combine(Application.dataPath, "Resources/Data/manager_improvements.json");
        JsonSerializer serializer    = new JsonSerializer();

        serializer.Formatting = Formatting.Indented;
        Serialize(serializePath, jsonData);
        Debug.Log("manager improvements saved...".Colored(ConsoleTextColor.orange).BoldItalic());
        EditorUtility.DisplayDialog("Manager improvements loaded", $"data saved to {"Resources/Data/manager_improvements.json"}", "Ok");
    }
Ejemplo n.º 13
0
        public bool IsTokenValid(string token)
        {
            var jsonSerializer = new JavaScriptSerializer();
            var decodedToken   = JsonWebToken.Decode(token, _authOptions.EncryptKey);
            var data           = jsonSerializer.Deserialize <Dictionary <string, object> >(decodedToken);

            if (!data.TryGetValue("exp", out var exp))
            {
                return(false);
            }

            if (!long.TryParse(exp.ToString(), out var unixTime))
            {
                return(false);
            }

            var validTo = unixTime.UnixTimeToDateTime();

            if (DateTime.Compare(validTo, DateTime.UtcNow) <= 0)
            {
                return(false);
            }

            return(true);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Assertion for token.
        /// </summary>
        /// <param name="role">The role of the user. Singular only!</param>
        /// <param name="user">The owner of the token</param>
        /// <param name="token">The token as string</param>
        /// <param name="checkId">Optional parameter on if the id should be checked</param>
        /// <exception cref="ArgumentNullException">If parameters are null</exception>
        private static void CheckToken(IdentityRole role, ApplicationUser user,
                                       string token, bool checkId = true)
        {
            if (role == null)
            {
                throw new ArgumentNullException(nameof(role));
            }
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            if (token == null)
            {
                throw new ArgumentNullException(nameof(token));
            }
            var check = checkId;
            var data  = JsonWebToken.Decode(token, new MockConfiguration()["SecretKey"]);
            var json  = JObject.Parse(data);

            Assert.Equal(user.Email, json.GetValue("sub"));
            if (check)
            {
                Assert.Equal(user.Id, json.GetValue(ClaimTypes.NameIdentifier));
            }
            Assert.Equal(user.Name, json.GetValue(ClaimTypes.Name));
            Assert.Equal(role.Name, json.GetValue(ClaimTypes.Role));
        }
Ejemplo n.º 15
0
        /// <summary>
        /// 检查用户令牌
        /// </summary>
        /// <param name="token">用户令牌</param>
        /// <param name="sharedKey">用于加密解密签名以及用户令牌的Key</param>
        /// <param name="tokenExpiredDays">用户令牌过期天数</param>
        /// <returns>
        /// 检查结果
        /// </returns>
        public Tuple <bool, string> ValidateToken(string token, string sharedKey, int tokenExpiredDays)
        {
            //返回的结果对象
            Tuple <bool, string> _checkeResult = new Tuple <bool, string>(false, "数据完整性检查不通过");

            if (!string.IsNullOrEmpty(token))
            {
                try
                {
                    string _decodedJwt = JsonWebToken.Decode(token, sharedKey);

                    if (!string.IsNullOrEmpty(_decodedJwt))
                    {
                        dynamic _root              = JObject.Parse(_decodedJwt);
                        string  _userid            = _root.userId;
                        double  _jwtcreated        = (double)_root.claim;
                        bool    _validTokenExpired = (new TimeSpan((int)(UnixEpochHelper.GetCurrentUnixTimestamp().TotalSeconds - _jwtcreated)).TotalDays) > tokenExpiredDays;

                        if (_validTokenExpired)
                        {
                            _checkeResult = new Tuple <bool, string>(false, "用户令牌失效.");
                        }

                        _checkeResult = new Tuple <bool, string>(true, _userid);
                    }
                }
                catch (SignatureVerificationException)
                {
                    _checkeResult = new Tuple <bool, string>(false, "用户令牌非法.");
                }
            }

            return(_checkeResult);
        }
        public ActionResult AuthTokenValidate(string token)
        {
            var key       = ConfigurationManager.AppSettings["Auth.SecretKey"];
            var authToken = JsonWebToken.Decode(token, key, true);

            return(Content(authToken.UserId));
        }
Ejemplo n.º 17
0
        private static ClaimsPrincipal ValidateToken(string token, string secret, bool checkExpiration)
        {
            var jsonSerializer = new JavaScriptSerializer();
            var payloadJson    = JsonWebToken.Decode(token, secret);
            var payloadData    = jsonSerializer.Deserialize <Dictionary <string, object> >(payloadJson);


            object exp;

            if (payloadData != null && (checkExpiration && payloadData.TryGetValue("exp", out exp)))
            {
                var validTo = FromUnixTime(long.Parse(exp.ToString()));
                if (DateTime.Compare(validTo, DateTime.UtcNow) <= 0)
                {
                    throw new Exception(
                              string.Format("Token is expired. Expiration: '{0}'. Current: '{1}'", validTo, DateTime.UtcNow));
                }
            }

            var subject = new ClaimsIdentity("Federation", ClaimTypes.Name, ClaimTypes.Role);

            var claims = new List <Claim>();

            if (payloadData != null)
            {
                foreach (var pair in payloadData)
                {
                    var claimType = pair.Key;

                    var source = pair.Value as ArrayList;

                    if (source != null)
                    {
                        claims.AddRange(from object item in source
                                        select new Claim(claimType, item.ToString(), ClaimValueTypes.String));

                        continue;
                    }

                    switch (pair.Key)
                    {
                    case "UserName":
                        claims.Add(new Claim(ClaimTypes.Name, pair.Value.ToString(), ClaimValueTypes.String));
                        break;

                    case "Role":
                        claims.Add(new Claim(ClaimTypes.Role, pair.Value.ToString(), ClaimValueTypes.String));
                        break;

                    default:
                        claims.Add(new Claim(claimType, pair.Value.ToString(), ClaimValueTypes.String));
                        break;
                    }
                }
            }

            subject.AddClaims(claims);
            return(new ClaimsPrincipal(subject));
        }
Ejemplo n.º 18
0
        public void Should_Decode_Token_To_Json_Encoded_String()
        {
            var expectedPayload = jsonSerializer.Serialize(customer);

            string decodedPayload = JsonWebToken.Decode(token, "ABC", false);

            Assert.AreEqual(expectedPayload, decodedPayload);
        }
Ejemplo n.º 19
0
 public object GetData(string token)
 {
     if (JsonWebToken.IsCorrectToken(token, secretKey))
     {
         return(JsonWebToken.Decode(token, secretKey));
     }
     return(null);
 }
Ejemplo n.º 20
0
        //private readonly string _syscode = System.Configuration.ConfigurationManager.AppSettings["_syscode"];
        //private readonly AppSettingsCfg _appsettings;
        //private readonly ISysPermissionService _permissionService;

        //public ILocalizationManager LocalizationManager { get; set; }



        //public MyAuthorizeFilterAttribute(ISysPermissionService permissionService,
        //                                  AppSettingsCfg appsettings)
        //{
        //    //LocalizationManager = NullLocalizationManager.Instance;
        //    _permissionService = permissionService;
        //    _appsettings = appsettings;
        //}

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            #region 优先排除不需要认证登录的属性
            MethodInfo methodinfo = (filterContext.ActionDescriptor as ControllerActionDescriptor).MethodInfo;
            Type       mtype      = filterContext.ActionDescriptor.GetType();
            //匿名访问,直接返回
            if (ReflectionHelper.GetAttributesOfMemberAndType(methodinfo, mtype).OfType <IAbpAllowAnonymousAttribute>().Any())
            {
                return;
            }
            if (ReflectionHelper.GetAttributesOfMemberAndType(methodinfo, mtype).OfType <IAllowAnonymous>().Any())
            {
                return;
            }
            //ABP认证的忽略
            //var authorizeAttributes = ReflectionHelper.GetAttributesOfMemberAndType(methodinfo, mtype).OfType<IAbpAuthorizeAttribute>().ToArray();
            //if (!authorizeAttributes.Any())
            //{
            //    return;
            //}
            //var methodCustomAttributes = methodinfo.GetCustomAttributes(true).ToList(); //获得所有自定义的attributes标记
            #endregion

            var path       = filterContext.HttpContext.Request.Path.ToString().ToLower();
            var isViewPage = false;//当前Action请求是否为具体的功能页


            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                string token = filterContext.HttpContext.Request.Headers["Authorization"].ToString().Substring("Bearer ".Length).Trim();

                //string cliamOrg = token.Split(".")[1];
                string re = JsonWebToken.Decode(token, "", false);

                //if ((filterContext.HttpContext.User.Claims.Count() > 0))
                //{

                //}
                throw new UserFriendlyException("认证失败", "你的登录信息不存在或是过期,请重新登录");
                //throw new AbpAuthorizationException(LocalizationManager.GetString(WebAppConsts.LocalizationSourceName, "CurrentUserDidNotLoginToTheApplication"));
                //var resultJson = new JsonResult(new
                //{
                //    success = false,
                //    msg = "抱歉:你的登录信息不存在,请重新登录"
                //});
                //filterContext.Result = resultJson;
            }
            else
            {
                //根据验证判断进行处理
                this.AuthorizeCore(filterContext, isViewPage);
            }
        }
Ejemplo n.º 21
0
 void Decode()
 {
     try {
         var result = JsonWebToken.Decode(token, secretKey, false);
         Debug.Log("Decode : " + result);
     } catch (SignatureVerificationException) {
         Debug.Log("Invalid Token");
     }
 }
Ejemplo n.º 22
0
        /// <summary>
        /// verify token info
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public bool VerifyToken(string token)
        {
            //获取用户信息
            var userNameAndPwd = JsonWebToken.Decode(token, key);

            //数据查询用户信息是否正确

            return(true);
        }
Ejemplo n.º 23
0
        public void Should_Decode_Token_To_Json_Encoded_String()
        {
            JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
            string expectedPayload = jsonSerializer.Serialize(_customer);

            string decodedPayload = JsonWebToken.Decode(_token, "ABC", false);

            Assert.AreEqual(expectedPayload, decodedPayload);
        }
Ejemplo n.º 24
0
        public void Should_Decode_Token_To_Json_Encoded_String()
        {
            var jsonSerializer  = new JavaScriptSerializer();
            var expectedPayload = jsonSerializer.Serialize(customer);

            string decodedPayload = defaultSerializer.Decode(token, "ABC", false);

            Assert.AreEqual(expectedPayload, decodedPayload);
        }
Ejemplo n.º 25
0
 public static titan_token  Decode(string JWT) {
     byte[] privateKey=get_certificate_private_key();   
     if(null==privateKey) {
         titan_token t=new titan_token();
         t.valid=false;
     }
     titan_token token= JsonWebToken.Decode(JWT,privateKey ,true);
     return token;
 }
Ejemplo n.º 26
0
        public void InvalidKey_ThrowsException()
        {
            // Arrange
            var token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJrZXkxIjoxLCJrZXkyIjoidGhlLXZhbHVlIn0.z4nWl_itwSsz1SbxEZkxCmm9MMkIKanFvgGz_gsWIJo";

            // Act & Assert
            var ex = Assert.Throws <SignatureVerificationException>(() => JsonWebToken.Decode(token, "invalid_key"));

            Assert.Equal("Invalid JWT signature.", ex.Message);
        }
Ejemplo n.º 27
0
        public void InvalidSignature_ThrowsException()
        {
            // Arrange
            var token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJrZXkxIjoxLCJrZXkyIjoidGhlLXZhbHVlIn0.nope";

            // Act & Assert
            var ex = Assert.Throws <SignatureVerificationException>(() => JsonWebToken.Decode(token, "SOME_SECRET_KEY"));

            Assert.Equal("Invalid JWT signature.", ex.Message);
        }
Ejemplo n.º 28
0
    private static void DownloadShipModulesBalance()
    {
        WebClient webClient = new WebClient();

        webClient.Headers.Add(HttpRequestHeader.Authorization, NetService.AuthHeader);
        string  downloadedString = webClient.DownloadString(NetService.FullUrl(NetService.balanceShipUrl));
        string  json             = JsonWebToken.Decode(downloadedString, NetService.secretKey);
        JObject parent           = JObject.Parse(json);
        JToken  arr = parent["response"]["data"];
        List <ShipModuleJsonData> modules = new List <ShipModuleJsonData>();
        int moduleId = 0;

        foreach (JToken token in arr)
        {
            int    planetLevel = token.Value <int>(0);
            double companyCash = token.Value <double>(1);
            double securities  = token.Value <double>(2);
            int    coins       = token.Value <int>(3);
            if (companyCash != 0.0)
            {
                modules.Add(new ShipModuleJsonData {
                    currencyType = CurrencyType.CompanyCash,
                    id           = moduleId,
                    planetLevel  = planetLevel,
                    price        = companyCash
                });
            }
            else if (securities != 0.0)
            {
                modules.Add(new ShipModuleJsonData {
                    currencyType = CurrencyType.Securities,
                    id           = moduleId,
                    planetLevel  = planetLevel,
                    price        = securities
                });
            }
            else
            {
                modules.Add(new ShipModuleJsonData {
                    currencyType = CurrencyType.Coins,
                    id           = moduleId,
                    planetLevel  = planetLevel,
                    price        = coins
                });
            }
            moduleId++;
        }

        string         serializePath = Path.Combine(Application.dataPath, "Resources/Data/ship_modules.json");
        JsonSerializer serializer    = new JsonSerializer();

        serializer.Formatting = Formatting.Indented;
        Serialize(serializePath, modules);
        Debug.Log("modules saved...");
    }
Ejemplo n.º 29
0
        public void Decode_Should_Decode_Token_To_Json_Encoded_String_With_JsonNet_Serializer()
        {
            var serializer = new JsonNetSerializer();

            JsonWebToken.JsonSerializer = serializer;

            var expectedPayload = serializer.Serialize(_customer);
            var actualPayload   = JsonWebToken.Decode(_token, "ABC", verify: false);

            actualPayload.Should().Be(expectedPayload);
        }
Ejemplo n.º 30
0
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            var    rdata = actionContext.ControllerContext?.RouteData;
            object mid;

            if (rdata == null || !rdata.Values.Any() || !rdata.Values.TryGetValue("merchantId", out mid))
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                return;
            }

            var authHeader = actionContext.Request.Headers.Authorization;

            if (authHeader == null ||
                !authHeader.Scheme.Equals("token", StringComparison.OrdinalIgnoreCase) ||
                string.IsNullOrWhiteSpace(authHeader.Parameter))
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                return;
            }
            var token    = authHeader.Parameter;
            var merchant = mid.ToString();

            //This is a mock lookup to obtain a merchant's shared secret
            if (merchant.Equals("MID001", StringComparison.Ordinal) || merchant.Equals("MID002", StringComparison.Ordinal))
            {
                //For mocking only. Merchant lookup from datastore will provide value
                var secret = AuthUtils.MOCK_SHARED_SECRET;

                try
                {
                    JsonWebToken.Decode(token, secret);
                }
                catch (SignatureVerificationException ex)
                {
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, ex.Message);
                    return;
                }
                catch (Exception ex)
                {
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
                    return;
                }
            }
            else
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                return;
            }



            base.OnAuthorization(actionContext);
        }