示例#1
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            ViewBag.Title = "JWT示例程序";

            const string key = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk";//私密key

            //1、生成JWT Token
            JWT.Algorithms.HMACSHA256Algorithm hMACSHA256Algorithm = new JWT.Algorithms.HMACSHA256Algorithm();
            JWT.Serializers.JsonNetSerializer  jsonNetSerializer   = new JWT.Serializers.JsonNetSerializer();
            JWT.JwtBase64UrlEncoder            jwtBase64UrlEncoder = new JWT.JwtBase64UrlEncoder();
            JWT.JwtEncoder jwtEncoder = new JWT.JwtEncoder(hMACSHA256Algorithm, jsonNetSerializer, jwtBase64UrlEncoder);

            //JWT三部分组成 header.payload.signature
            Dictionary <string, object> dictHeader = new Dictionary <string, object>()//header
            {
            };

            DateTime dtExpire = DateTime.UtcNow.AddSeconds(15);                       //为了测试过期可以把过期时间设置为1秒钟
            double   exp      = (dtExpire - JWT.JwtValidator.UnixEpoch).TotalSeconds; //注意,这里用的是UTC时间

            object payload = new Models.Payload <Models.User>()
            {
                exp  = exp,
                data = new Models.User()
                {
                    Id     = Guid.Parse("e05aa9d2-6a97-4df1-ab81-b1b585e9bc44"),
                    Name   = "lichaoqiang",
                    Mobile = "13503879XXX",
                    Email  = "*****@*****.**",
                    Role   = "admin",
                }
            };//负载

            try
            {
                string strJwtToken = jwtEncoder.Encode(payload, key);

                //2、验证JWT Token
                JWT.JwtValidator jwtValidator = new JWT.JwtValidator(jsonNetSerializer, new JWT.UtcDateTimeProvider());//jwtValidator
                JWT.JwtDecoder   jwtDecoder   = new JWT.JwtDecoder(jsonNetSerializer, jwtValidator, jwtBase64UrlEncoder);

                var payloadData = jwtDecoder.DecodeToObject <Models.Payload <Models.User> >(token: strJwtToken);//从JWTToken中反序列化负荷

                byte[]       keys     = System.Text.Encoding.UTF8.GetBytes(key);
                JWT.JwtParts jwtParts = new JWT.JwtParts(token: strJwtToken);
                jwtDecoder.Validate(jwtParts, keys);
            }
            catch (JWT.TokenExpiredException ex)
            {
                //令牌过期
            }
            catch (JWT.SignatureVerificationException ex)
            {
                //签名失败
            }
            catch (Exception ex)
            {
            }
            return(View());
        }
示例#2
0
        public static string Encode(object target)
        {
            JWT.Algorithms.HMACSHA256Algorithm algorithm  = new JWT.Algorithms.HMACSHA256Algorithm();
            JWT.Serializers.JsonNetSerializer  serializer = new JWT.Serializers.JsonNetSerializer();
            JWT.JwtBase64UrlEncoder            urlEncoder = new JWT.JwtBase64UrlEncoder();
            JWT.JwtEncoder encoder = new JWT.JwtEncoder(algorithm, serializer, urlEncoder);
            var            token   = encoder.Encode(target, key);

            return(token);
        }
示例#3
0
        public static T Decode <T>(string token)
        {
            JWT.Serializers.JsonNetSerializer serializer = new JWT.Serializers.JsonNetSerializer();
            JWT.UtcDateTimeProvider           provider   = new JWT.UtcDateTimeProvider();
            JWT.JwtValidator        validator            = new JWT.JwtValidator(serializer, provider);
            JWT.JwtBase64UrlEncoder urlEncoder           = new JWT.JwtBase64UrlEncoder();
            JWT.JwtDecoder          decoder = new JWT.JwtDecoder(serializer, validator, urlEncoder);
            T target = decoder.DecodeToObject <T>(token, key, true);

            return(target);
        }
示例#4
0
        private string GenerateNewTokenForUser(string email)
        {
            var payload = new Dictionary <string, object>
            {
                { "email", email }
            };

            JWT.IJwtAlgorithm     algorithm  = new HMACSHA256Algorithm();
            JWT.IJsonSerializer   serializer = new JsonNetSerializer();
            JWT.IBase64UrlEncoder urlEncoder = new JWT.JwtBase64UrlEncoder();
            JWT.IJwtEncoder       encoder    = new JWT.JwtEncoder(algorithm, serializer, urlEncoder);

            var token = encoder.Encode(payload, secret);

            return(token);
        }
示例#5
0
        public string verifyUserToken()
        {
            string token = Request.Headers["token"];

            try
            {
                JWT.IJsonSerializer   serializer = new JsonNetSerializer();
                JWT.IDateTimeProvider provider   = new JWT.UtcDateTimeProvider();
                JWT.IJwtValidator     validator  = new JWT.JwtValidator(serializer, provider);
                JWT.IBase64UrlEncoder urlEncoder = new JWT.JwtBase64UrlEncoder();
                JWT.IJwtDecoder       decoder    = new JWT.JwtDecoder(serializer, validator, urlEncoder);

                var json = decoder.Decode(token, secret, verify: true);
                return("ok");
            }
            catch (JWT.TokenExpiredException)
            {
                return("Token has expired");
            }
            catch (JWT.SignatureVerificationException)
            {
                return("Token has invalid signature");
            }
        }
示例#6
0
        public ActionResult MobileView()
        {
            string tmpCode = this.GetQueryString("TmplCode");
            string title   = this.GetQueryString("Title");

            if (!string.IsNullOrEmpty(title))
            {
                ViewBag.Title = title;
            }
            else
            {
                ViewBag.Title = "图表";
            }
            string tokenKey = !String.IsNullOrEmpty(ConfigurationManager.AppSettings["TokenKey"]) ? ConfigurationManager.AppSettings["TokenKey"] : "GWToken";
            var    token    = this.GetQueryString(tokenKey);

            if (!String.IsNullOrEmpty(token))
            {
                //根据密钥解析token,获取用户信息
                var secretKey = String.IsNullOrEmpty(ConfigurationManager.AppSettings["SecretKey"]) ? String.Empty : ConfigurationManager.AppSettings["SecretKey"];
                if (String.IsNullOrEmpty(secretKey))
                {
                    throw new Formula.Exceptions.BusinessException("系统未设置密钥,进行验证操作");
                }
                JWT.IJsonSerializer   serializer = new JWT.Serializers.JsonNetSerializer();
                JWT.IDateTimeProvider provider   = new JWT.UtcDateTimeProvider();
                JWT.IJwtValidator     validator  = new JWT.JwtValidator(serializer, provider);
                JWT.IBase64UrlEncoder urlEncoder = new JWT.JwtBase64UrlEncoder();
                JWT.IJwtDecoder       decoder    = new JWT.JwtDecoder(serializer, validator, urlEncoder);
                //var key = Convert.ToBase64String(Encoding.UTF8.GetBytes(secretKey));
                var json    = decoder.Decode(token, secretKey, verify: true);
                var dic     = Formula.Helper.JsonHelper.ToObject(json);
                var sysName = dic.GetValue("systemName");

                //判断是否过期
                bool isExpire = false;
                if (!String.IsNullOrEmpty(dic.GetValue("ExpiredTime")))
                {
                    //兼容以前用自定义字段判断过期时间的写法,目前使用JWT固有的判断超时的字段“exp”,JWT校验的时候会失效,不用写代码判断是否失效
                    var expirationTime = String.IsNullOrEmpty(dic.GetValue("ExpiredTime")) ? DateTime.Now : Convert.ToDateTime(dic.GetValue("ExpiredTime"));
                    isExpire = DateTime.Now > expirationTime;
                }
                FormulaHelper.SetAuthCookie(sysName);
            }
            else
            {
                var sysName = this.GetQueryString("Account");
                FormulaHelper.SetAuthCookie(sysName);
                if (!Formula.AuthCodeHelper.CheckTokenRole() && !string.IsNullOrEmpty(sysName))
                {
                    return(Redirect(HttpContext.Request.Url.ToString()));
                }
            }


            var config = this.entities.Set <S_UI_BIConfig>().FirstOrDefault(d => d.Code == tmpCode);

            if (config == null)
            {
                throw new Exception("未能找到编号为【" + tmpCode + "】的BI定义对象");
            }
            var layout = JsonHelper.ToList(config.Layout);
            var blocks = JsonHelper.ToList(config.Blocks);

            foreach (var item in blocks)
            {
                //去除DataSource属性不在页面数据岛上显示,以避免防止SQL注入攻击
                var settings = JsonHelper.ToObject(item.GetValue("Settings"));
                settings.Remove("dataSource");
                if (JsonHelper.ToJson(settings).IndexOf("FilterInfo") >= 0)
                {
                    var FilterInfo = JsonHelper.ToList(settings["FilterInfo"].ToString());
                    for (int i = 0; i < FilterInfo.Count(); i++)
                    {
                        if (JsonHelper.ToJson(FilterInfo[i]).IndexOf("EnumData") >= 0 && !string.IsNullOrEmpty(FilterInfo[i]["EnumData"].ToString()) && FilterInfo[i]["EnumData"].ToString().IndexOf("{") < 0)
                        {
                            IEnumService enumService = FormulaHelper.GetService <IEnumService>();
                            FilterInfo[i]["EnumData"] = JsonHelper.ToJson(enumService.GetEnumDataSource(FilterInfo[i]["EnumData"].ToString()));
                        }
                    }
                    settings["FilterInfo"] = FilterInfo;
                }
                item.SetValue("Settings", JsonHelper.ToJson(settings));
            }
            ViewBag.LayOutInfo   = layout;
            ViewBag.Blocks       = blocks;
            ViewBag.PageTitle    = "";
            ViewBag.LayOutJson   = config.Layout;
            ViewBag.BlocksJson   = JsonHelper.ToJson(blocks);
            ViewBag.RowsCount    = layout.Count;
            ViewBag.ColumnsCount = layout.Count == 0 ? 0 : layout.Max(c => Convert.ToInt32(c["ColumnNumber"]));
            var templateInfo = new Dictionary <string, object>();

            foreach (var item in blocks)
            {
                var    BlockType = item.GetValue("BlockType");
                string filePath  = HttpContext.Server.MapPath(String.Format("/MvcConfig/Scripts/BI/template/div/{0}.html", BlockType));
                if (System.IO.File.Exists(filePath))
                {
                    FileStream   fs      = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                    StreamReader reader  = new StreamReader(fs);
                    var          divHtml = reader.ReadToEnd();
                    reader.Close();
                    fs.Close();
                    item.SetValue("divHtml", MvcHtmlString.Create(divHtml));
                }
                if (!templateInfo.ContainsKey(BlockType))
                {
                    string templatefilePath = HttpContext.Server.MapPath(String.Format("/MvcConfig/Scripts/BI/template/templ/{0}.html", BlockType));
                    if (System.IO.File.Exists(templatefilePath))
                    {
                        FileStream   tmplfs     = new FileStream(templatefilePath, FileMode.Open, FileAccess.Read);
                        StreamReader tmplreader = new StreamReader(tmplfs);
                        var          tmplHtml   = tmplreader.ReadToEnd();
                        tmplreader.Close();
                        tmplfs.Close();
                        templateInfo.SetValue(BlockType, MvcHtmlString.Create(tmplHtml));
                    }
                }
            }
            ViewBag.Script        = HttpContext.Server.HtmlDecode(config.ScriptText);
            ViewBag.BlockTemplate = templateInfo;
            ViewBag.FullScreen    = false;
            if (this.GetQueryString("FullScreen").Trim().ToLower() == true.ToString().ToLower())
            {
                ViewBag.FullScreen = true;
            }
            return(View());
        }