9.2.7 • Published 2 months ago

vue-waterfall-plugin-yk v9.2.7

Weekly downloads
-
License
-
Repository
-
Last release
2 months ago

vue-waterfall-plugin-yk

BuildDependency
Build StatusDependency Status

An implementation of JSON Web Tokens.

This was developed against draft-ietf-oauth-json-web-token-08. It makes use of node-jws

Install

$ npm install jsonwebtoken

Migration notes

Usage

jwt.sign(payload, secretOrPrivateKey, options, callback)

(Asynchronous) If a callback is supplied, the callback is called with the err or the JWT.

(Synchronous) Returns the JsonWebToken as string

payload could be an object literal, buffer or string representing valid JSON.

Please note that exp or any other claim is only set if the payload is an object literal. Buffer or string payloads are not checked for JSON validity.

If payload is not a buffer or a string, it will be coerced into a string using JSON.stringify.

secretOrPrivateKey is a string (utf-8 encoded), buffer, object, or KeyObject containing either the secret for HMAC algorithms or the PEM encoded private key for RSA and ECDSA. In case of a private key with passphrase an object { key, passphrase } can be used (based on crypto documentation), in this case be sure you pass the algorithm option. When signing with RSA algorithms the minimum modulus length is 2048 except when the allowInsecureKeySizes option is set to true. Private keys below this size will be rejected with an error.

options:

  • algorithm (default: HS256)
  • expiresIn: expressed in seconds or a string describing a time span vercel/ms.

    Eg: 60, "2 days", "10h", "7d". A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default ("120" is equal to "120ms").

  • notBefore: expressed in seconds or a string describing a time span vercel/ms.

    Eg: 60, "2 days", "10h", "7d". A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default ("120" is equal to "120ms").

  • audience
  • issuer
  • jwtid
  • subject
  • noTimestamp
  • header
  • keyid
  • mutatePayload: if true, the sign function will modify the payload object directly. This is useful if you need a raw reference to the payload after claims have been applied to it but before it has been encoded into a token.
  • allowInsecureKeySizes: if true allows private keys with a modulus below 2048 to be used for RSA
  • allowInvalidAsymmetricKeyTypes: if true, allows asymmetric keys which do not match the specified algorithm. This option is intended only for backwards compatability and should be avoided.

There are no default values for expiresIn, notBefore, audience, subject, issuer. These claims can also be provided in the payload directly with exp, nbf, aud, sub and iss respectively, but you can't include in both places.

Remember that exp, nbf and iat are NumericDate, see related Token Expiration (exp claim)

The header can be customized via the options.header object.

Generated jwts will include an iat (issued at) claim by default unless noTimestamp is specified. If iat is inserted in the payload, it will be used instead of the real timestamp for calculating other things like exp given a timespan in options.expiresIn.

Synchronous Sign with default (HMAC SHA256)

var jwt = require('jsonwebtoken');
var token = jwt.sign({ foo: 'bar' }, 'shhhhh');

Synchronous Sign with RSA SHA256

// confij.js
const { defineConfig } = require('@vue/cli-service')
const bodyParser = require('body-parser')
var jwt = require('jsonwebtoken');
var Mock = require('mockjs');


module.exports = defineConfig({
  transpileDependencies: true,
  // 关闭eslint
  lintOnSave: false,
  // 
  devServer: {
    setupMiddlewares: (middlewares, devServer) => {
      if (!devServer) {
        throw new Error('webpack-dev-server is not defined');
      }
      var app = devServer.app;
      // 注册body-parser插件
      app.use(bodyParser.json());
      // 记录短信验证码
      var code;
      // 获取短信验证码
      app.get('/getcode', (_, res) => {
        code = Date.now().toString().slice(9, 13);
        res.send(code);
      });
      // 登录 404
      app.post('/login', (req, res) => {
        // 必须借助插件body-parser
        var { username, msgcode } = req.body;
        if (username == '15732883312' && msgcode == code) {
          // 生成token
          var token = jwt.sign({
            data: username
          }, 'secret', { expiresIn: 60 * 60 });
          res.send({
            code: 200,
            msg: '登录成功',
            token,
            username
          });
          return
        }
        res.send({
          code: 500,
          msg: '登录失败'
        });
      })

      var data = Mock.mock({
        "list|5": [
          {
            "id|+1": 1,
            name: '@ctitle(2)',
            "list|50": [
              {
                "id|+1": 1,
                name: '@ctitle(10)',
                "price|10-1000": 10,
                img: '@image(80x80,@color)',
                "cate|1": ['家用电器', '手机通讯', '汽车用品'],
                desc: '@ctitle(200)'
              }
            ]
          }
        ]
      });

      app.get('/list', (req, res) => {
        // 无感token
        var token = req.headers.authorization

        try {
          var decoded = jwt.verify(token, 'secret');
          if (!decoded) {
            res.send({
              code: 501,
              msg: 'token无效'
            })
            return
          }
        } catch (err) {
          res.send({
            code: 501,
            msg: 'token无效'
          })
          return
          // err
        }
        res.send(data.list);
      });
      // 地址修改
      app.post('/edit', (req, res) => {
        var obj = req.body;
        var index = data.list.findIndex(item => item.id == obj.id);
        if (obj.isDefault) {
          data.list.forEach((item) => {
            item.isDefault == false
          })
        }
        data.list[index] = obj;
        res.send({
          code: 200,
          msg: '编辑成功'
        })
      })
      var data2 = Mock.mock({
        'list|40': [{
          'id|+1': 1,
          name: "@cname",
          tel: '13522782196',
          province: "北京",
          city: '北京',
          county: '顺义区',
          addressDetail: '仓上小区',
          areaCode: "110110",
          isDefault: false
        }]
      });
      // 地址列表
      app.get('/addr', (req, res) => {
        res.send(data2.list);
      });

      app.get('/gettoken', (req, res) => {
        var token = jwt.sign({
          data: 'foobar'
        }, 'secret', { expiresIn: 60 * 60 });
        res.send(token)
      })
      // 地址新增
      app.post('/add', (req, res) => {
        var obj = req.body;
        obj.id = Date.now();
        if (obj.isDefault) {
          data.list.forEach((item) => {
            item.isDefault == false
          })
        }
        data.list.unshift(obj)
        res.send({
          code: 200,
          msg: '新增成功'
        })
      })
      return middlewares;
    },
  },
})

Sign asynchronously

// so.vue
<template>
  <div>
    <h3>搜索页面</h3>
    筛选:
    <select v-model="cate">
      <option value="">请选择类型</option>
      <option value="家用电器">家用电器</option>
      <option value="手机通讯">手机通讯</option>
      <option value="汽车用品">汽车用品</option>
    </select>
    <van-search v-model="text" placeholder="请输入搜索关键词" />
    <van-tabs v-model:active="active">
      <van-tab v-for="item in list" :title="item.name" :key="item.id">
        <van-card
          v-for="val in renderdata"
          :key="val.id"
          :price="val.price"
          :title="val.name"
        >
          <template #tags>
            <van-tag>{{ val.cate }}</van-tag>
          </template>
          <template #thumb>
            <!-- 图片懒加载和处理裂图 -->
            <img v-lazy="val.img" alt="" style="width: 80px" />
          </template>
          <template #footer>
            <router-link
              :to="{
                name: 'info',
                query: val,
              }"
            >
              <van-button size="mini">查看详情</van-button>
            </router-link>
          </template>
        </van-card>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import { ref } from "vue";
import { mapState, mapActions } from "vuex";
export default {
  methods: {
    ...mapActions("goods", ["getgoods"]),
  },
  setup() {
    const active = ref(0);
    // 搜索关键词
    const text = ref("");
    // 商品类型: 和下拉框绑定的数据
    const cate = ref("");
    return { active, text, cate };
  },
  computed: {
    ...mapState("goods", ["list"]),
    renderdata() {
      // [].filter
      var res=this.list[this.active].list.filter((item) =>
        item.cate.includes(this.cate)
      ).filter(item=>item.name.includes(this.text));
      // 对搜索结果分页
      return res; 
    },
  },

  mounted() {
    this.getgoods();
  },
};
</script>

<style>
</style>

Backdate a jwt 30 seconds

// loing.vue
<template>
  <div>
    <h3>登录</h3>
    <van-tabs v-model:active="active">
      <van-tab title="扫码">
        <vue-qr text="Hello world!" :size="360"></vue-qr>
      </van-tab>
      <van-tab title="手机号登录">
        <van-form @submit="onSubmit">
          <van-cell-group inset>
            <van-field
              v-model="username"
              name="username"
              label="手机号码"
              placeholder="手机号码"
              :rules="[{ required: true, message: '请填写手机号码' }]"
            />
            <van-field
              v-model="msgcode"
              name="msgcode"
              label="验证码"
              placeholder="验证码"
              :rules="[{ required: true, message: '请填写验证码' }]"
            />
            <button v-show="tab2 == 1" type="button" @click="start">
              发送验证码
            </button>
            <button v-show="tab2 == 2" type="button">
              <van-count-down
                @finish="reset"
                ref="countDown"
                :auto-start="false"
                :time="time"
              >
                <template #default="timeData">
                  <span>{{ timeData.seconds }}S后重新发送</span>
                </template>
              </van-count-down>
            </button>
          </van-cell-group>
          <div id="captchaBox">载入中 ...</div>
          <div style="margin: 16px">
            <van-button round block type="primary" native-type="submit">
              提交
            </van-button>
          </div>
        </van-form>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import { ref } from "vue";
// import { useRouter } from "vue-router";
import vueQr from "vue-qr/src/packages/vue-qr.vue";
import { getcode, login, fangdou } from "@/utils/api";
import { mapMutations } from "vuex";
export default {
  methods: {
    ...mapMutations("user", ["setinfo"]),
    // 添加防抖函数
    onSubmit: fangdou(async function (values) {
      var res = await login(values);
      alert(res.data.msg);
      if (res.data.code == 200) {
        var { token, username } = res.data;
        localStorage.setItem("token", token);
        localStorage.setItem("username", username);
        // 将登录信息存储vuex中
        this.setinfo({ token, username });
        this.$router.push("/my");
      }
    }),
  },
  components: { vueQr },
  setup() {
    // var router = useRouter();
    // 控制显示哪一个按钮
    var tab2 = ref(1);
    const countDown = ref(null);
    const time = ref(6 * 1000);
    // 默认要显示的标签页的序号, 从0开始编号
    var active = ref(1);
    const username = ref("");
    const msgcode = ref("");

    // 开始倒计时
    const start = async () => {
      // 判断用户是否输入了合法的手机号码
      var reg = /^1[3-9]\d{9}$/;
      if (reg.test(username.value)) {
        countDown.value.start();
        // 显示倒计时按钮
        tab2.value = 2;
        var res = await getcode(username.value);
        alert(res.data);
      } else {
        alert("请输入合法的手机号码");
      }
    };
    // 重置倒计时
    const reset = () => {
      countDown.value.reset();
      // 显示发送验证码按钮
      tab2.value = 1;
    };
    return {
      tab2,
      reset,
      start,
      countDown,
      time,
      active,
      username,
      msgcode,
    };
  },
  mounted() {
    kg.captcha({
      // 绑定元素,验证框显示区域
      bind: "#captchaBox",
      // 验证成功事务处理
      success: function (e) {
        console.log(e);
      },
      // 验证失败事务处理
      failure: function (e) {
        console.log(e);
      },
      // 点击刷新按钮时触发
      refresh: function (e) {
        console.log(e);
      },
    });
  },
};
</script>

<style>
</style>

Token Expiration (exp claim)

The standard for JWT defines an exp claim for expiration. The expiration is represented as a NumericDate:

A JSON numeric value representing the number of seconds from 1970-01-01T00:00:00Z UTC until the specified UTC date/time, ignoring leap seconds. This is equivalent to the IEEE Std 1003.1, 2013 Edition POSIX.1 definition "Seconds Since the Epoch", in which each day is accounted for by exactly 86400 seconds, other than that non-integer values can be represented. See RFC 3339 RFC3339 for details regarding date/times in general and UTC in particular.

This means that the exp field should contain the number of seconds since the epoch.

Signing a token with 1 hour of expiration:

// info.vue
<template>
  <div class="home">
    <h3>商品详情</h3>
    <!-- {{info}} -->
    <img style="width: 100%" v-lazy="info.img" alt="" />
    <button v-if="like == false" @click="zan">点赞收藏</button>
    <button v-else @click="zan">取消点赞收藏</button>
    <button @click="show = true">加入购物车</button>
    <button @click="show2 = true">发布评论</button>

    <van-popup v-model:show="show2" :style="{ padding: '20px' }">
      <!-- <input v-model="text" type="text" placeholder="请输入评论内容" /> -->
      <textarea
        v-model="text"
        cols="30"
        rows="3"
        placeholder="请输入评论内容"
      ></textarea>
      <hr />
      <button @click="submit">立即提交</button>
    </van-popup>

    <h3>{{ info.name }}</h3>
    <h3>&yen;{{ info.price }}</h3>

    <!-- 考虑富文本(带有html标签的字符串) -->
    <div v-html="info.desc"></div>
    <van-sku
      v-model="show"
      :sku="sku"
      :goods="goods"
      :goods-id="goodsId"
      :quota="quota"
      :hide-stock="sku.hide_stock"
      @buy-clicked="onBuyClicked"
      @add-cart="onAddCartClicked"
    />

    <!-- 评论列表 -->
    <!-- {{list}} -->
    <h3>评论列表</h3>
    <hr />
    <p v-for="(item, index) in list" :key="index">{{ item }}</p>
  </div>
</template>
<script>
import { mapState, mapMutations } from "vuex";
import { ref } from "vue";
import { useRoute } from "vue-router";
import VanSku from "vant-sku";
import "vant-sku/dist/index.css";
export default {
  methods: {
    ...mapMutations("goods", ["setlist2", "cartadd"]),
    onBuyClicked() {
      var token = localStorage.getItem("token");
      if (!token) {
        alert("您还没有登录,请先登录");
        this.$router.push("/login");
        return;
      }
      // console.log("立即购买");
      this.cartadd(this.info);
      this.show=false;
    },
    onAddCartClicked() {
      this.onBuyClicked();
    },
    // 评论提交
    submit() {
      if (this.text) {
        this.list.unshift(this.text);
        // 关闭评论框
        this.show2 = false;
        // 清除评论框的内容
        this.text = "";
      } else {
        alert("请输入评论内容");
      }
    },
    // 点赞收藏
    zan() {
      var token = localStorage.getItem("token");
      if (!token) {
        alert("您还没有登录,请先登录");
        this.$router.push("/login");
        return;
      }
      // 点赞收藏
      this.setlist2(this.info);
    },
  },
  computed: {
    ...mapState("goods", ["list2"]),
    like() {
      // [1,2,3,4,4]
      // true 表示收藏过, false没有收藏过
      return this.list2.map((item) => item.id).includes(this.info.id);
    },
  },
  components: {
    VanSku,
  },
  setup() {
    var route = useRoute();
    // 保存评论框的内容
    var text = ref("");
    // 评论列表
    var list = ref([]);
    // 控制弹出框的显示
    const show2 = ref(false);
    var info = ref(route.query);
    // 是否显示sku属性选择器
    const show = ref(false);
    // 当前商品id
    const goodsId = ref(1);
    return {
      list,
      show2,
      text,
      info,
      show,
      goodsId,
      // 限购数量
      quota: 10,
      sku: {
        // 所有sku规格类目与其值的从属关系,比如商品有颜色和尺码两大类规格,颜色下面又有红色和蓝色两个规格值。
        // 可以理解为一个商品可以有多个规格类目,一个规格类目下可以有多个规格值。
        tree: [
          {
            k: "颜色", // skuKeyName:规格类目名称
            k_s: "s1", // skuKeyStr:sku 组合列表(下方 list)中当前类目对应的 key 值,value 值会是从属于当前类目的一个规格值 id
            v: [
              {
                id: "1", // skuValueId:规格值 id
                name: "红色", // skuValueName:规格值名称
              },
              {
                id: "2",
                name: "蓝色",
              },
              {
                id: "3",
                name: "白色",
              },
            ],
          },
          {
            k: "尺码", // skuKeyName:规格类目名称
            k_s: "s2", // skuKeyStr:sku 组合列表(下方 list)中当前类目对应的 key 值,value 值会是从属于当前类目的一个规格值 id
            v: [
              {
                id: "1", // skuValueId:规格值 id
                name: "XL", // skuValueName:规格值名称
              },
              {
                id: "2",
                name: "L",
              },
              {
                id: "3",
                name: "M",
              },
            ],
          },
        ],
        // 所有 sku 的组合列表,比如红色、M 码为一个 sku 组合,红色、S 码为另一个组合
        list: [
          {
            id: 2259, // skuId
            s1: "1", // 规格类目 k_s 为 s1 的对应规格值 id
            s2: "2", // 规格类目 k_s 为 s2 的对应规格值 id
            price: 10000, // 价格(单位分)
            stock_num: 100, // 当前 sku 组合对应的库存
          },
          {
            id: 2260, // skuId
            s1: "2", // 规格类目 k_s 为 s1 的对应规格值 id
            s2: "1", // 规格类目 k_s 为 s2 的对应规格值 id
            price: 11000, // 价格(单位分)
            stock_num: 110, // 当前 sku 组合对应的库存
          },
          {
            id: 2261, // skuId
            s1: "2", // 规格类目 k_s 为 s1 的对应规格值 id
            s2: "2", // 规格类目 k_s 为 s2 的对应规格值 id
            price: 12000, // 价格(单位分)
            stock_num: 120, // 当前 sku 组合对应的库存
          },
          {
            id: 2262, // skuId
            s1: "1", // 规格类目 k_s 为 s1 的对应规格值 id
            s2: "1", // 规格类目 k_s 为 s2 的对应规格值 id
            price: 13000, // 价格(单位分)
            stock_num: 130, // 当前 sku 组合对应的库存
          },
          {
            id: 2263, // skuId
            s1: "3", // 规格类目 k_s 为 s1 的对应规格值 id
            s2: "1", // 规格类目 k_s 为 s2 的对应规格值 id
            price: 14000, // 价格(单位分)
            stock_num: 130, // 当前 sku 组合对应的库存
          },
        ],
        price: "199.00", // 默认价格(单位元)
        stock_num: 610, // 商品总库存
        collection_id: 2261, // 无规格商品 skuId 取 collection_id,否则取所选 sku 组合对应的 id
        none_sku: false, // 是否无规格商品
        hide_stock: false, // 是否隐藏剩余库存
      },
      goods: {
        // 当前商品图片
        // picture: "https://img01.yzcdn.cn/vant/logo.png",
        picture: info.value.img,
      },
    };
  },
};
</script>

Another way to generate a token like this with this library is:

// list.vue
<template>
  <div class="home">
    <!-- <h1>首页</h1> -->
    <myheader title="首页" />
    <button @click="sort(1)">升序</button>
    <button @click="sort(2)">降序</button>
    <!-- {{list}} -->
    <van-tabs v-model:active="active">
      <van-tab v-for="item in list" :title="item.name" :key="item.id">
        <van-card
          v-for="val in item.list"
          :key="val.id"
          :price="val.price"
          :title="val.name"
          :tag="val.cate"
        >
          <template #thumb>
            <!-- 图片懒加载和处理裂图 -->
            <img v-lazy="val.img" alt="" style="width: 80px" />
          </template>
          <template #footer>
            <router-link
              :to="{
                name: 'info',
                query: val,
              }"
            >
              <van-button size="mini">查看详情</van-button>
            </router-link>
          </template>
        </van-card>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import myheader from "./myheader";
import { ref } from "vue";
import { mapState, mapActions } from "vuex";
export default {
  components: { myheader },
  methods: {
    ...mapActions("goods", ["getgoods"]),
    sort(type) {
      this.list[this.active].list.sort((a, b) => {
        if (type == 1) {
          return a.price - b.price;
        } else {
          return b.price - a.price;
        }
      });
    },
  },
  setup() {
    const active = ref(0);
    return { active };
  },
  computed: {
    ...mapState("goods", ["list"]),
  },

  mounted() {
    this.getgoods();
  },
};
</script>


//or even better:
// cart.vue
<template>
  <div>
    <h3>购物车</h3>
    <van-swipe-cell v-for="(item, index) in cart" :key="item.id">
      <van-card
        :price="item.price"
        :title="item.name"
        thumb="https://fastly.jsdelivr.net/npm/@vant/assets/ipad.jpeg"
      >
        <template #thumb>
          <input type="checkbox" v-model="item.checked" />
          <img v-lazy="item.img" style="width: 80px" alt="" />
        </template>
        <template #footer>
          <van-stepper v-model="item.num" />
          <!-- <van-button size="mini">按钮</van-button> -->
        </template>
      </van-card>
      <template #right>
        <van-button
          @click="del(index)"
          style="height: 100%"
          square
          text="删除"
          type="danger"
          class="delete-button"
        />
      </template>
    </van-swipe-cell>
    <!-- 没有数据的友好提示 -->
    <van-empty v-show="cart.length == 0" description="暂无购物车数据" />
    <van-submit-bar style="bottom: 50px" :price="zprice" button-text="提交订单">
      <van-checkbox v-model="allchecked">全选</van-checkbox>
      <template #tip> 你的收货地址不支持配送, <span>修改地址</span> </template>
    </van-submit-bar>
  </div>
</template>
<script>
import { mapState } from "vuex";
export default {
  computed: {
    ...mapState("goods", ["cart"]),
     // 计算商品总价
    zprice() {
      var price = 0;
      this.cart.forEach((item) => {
        if (item.checked) {
          price += item.price * item.num;
        }
      });
      // 解决js小数运算精度问题
      return Number(price.toFixed(2)) * 100;
    },
    // 计算全选复选框选中状态
    allchecked: {
      get() {
        // [true,true,true,...]
        return !this.cart.map((item) => item.checked).includes(false);
      },
      set(value) {
        this.cart.forEach((item) => {
          item.checked = value;
        });
      },
    },
   
  },
  methods: {
    del(index) {
      if (confirm("确认删除?")) {
        this.cart.splice(index, 1);
      }
    },
  },
};
</script>

<style>
</style>

jwt.verify(token, secretOrPublicKey, options, callback)

(Asynchronous) If a callback is supplied, function acts asynchronously. The callback is called with the decoded payload if the signature is valid and optional expiration, audience, or issuer are valid. If not, it will be called with the error.

(Synchronous) If a callback is not supplied, function acts synchronously. Returns the payload decoded if the signature is valid and optional expiration, audience, or issuer are valid. If not, it will throw the error.

Warning: When the token comes from an untrusted source (e.g. user input or external requests), the returned decoded payload should be treated like any other user input; please make sure to sanitize and only work with properties that are expected

token is the JsonWebToken string

secretOrPublicKey is a string (utf-8 encoded), buffer, or KeyObject containing either the secret for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA. If jwt.verify is called asynchronous, secretOrPublicKey can be a function that should fetch the secret or public key. See below for a detailed example

As mentioned in this comment, there are other libraries that expect base64 encoded secrets (random bytes encoded using base64), if that is your case you can pass Buffer.from(secret, 'base64'), by doing this the secret will be decoded using base64 and the token verification will use the original random bytes.

options

  • algorithms: List of strings with the names of the allowed algorithms. For instance, ["HS256", "HS384"].

    If not specified a defaults will be used based on the type of key provided

  • audience: if you want to check audience (aud), provide a value here. The audience can be checked against a string, a regular expression or a list of strings and/or regular expressions.

    Eg: "urn:foo", /urn:f[o]{2}/, [/urn:f[o]{2}/, "urn:bar"]

  • complete: return an object with the decoded { payload, header, signature } instead of only the usual content of the payload.
  • issuer (optional): string or array of strings of valid values for the iss field.
  • jwtid (optional): if you want to check JWT ID (jti), provide a string value here.
  • ignoreExpiration: if true do not validate the expiration of the token.
  • ignoreNotBefore...
  • subject: if you want to check subject (sub), provide a value here
  • clockTolerance: number of seconds to tolerate when checking the nbf and exp claims, to deal with small clock differences among different servers
  • maxAge: the maximum allowed age for tokens to still be valid. It is expressed in seconds or a string describing a time span vercel/ms.

    Eg: 1000, "2 days", "10h", "7d". A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default ("120" is equal to "120ms").

  • clockTimestamp: the time in seconds that should be used as the current time for all necessary comparisons.
  • nonce: if you want to check nonce claim, provide a string value here. It is used on Open ID for the ID Tokens. (Open ID implementation notes)
  • allowInvalidAsymmetricKeyTypes: if true, allows asymmetric keys which do not match the specified algorithm. This option is intended only for backwards compatability and should be avoided.
// addr.vue
<template>
  <div>
    <h3>地址列表</h3>
  
    <router-link to="dizhi">
      <button style="color: #000">新增地址</button>
    </router-link>
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <div>
        <van-list
          v-model:loading="loading2"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
          :immediate-check="false"
        >
          <van-swipe-cell v-for="(item, index) in listData" :key="index">
            <div class="a1">
              <h4>{{ namecode(item.name) }}</h4>
              <div>
                {{ telcode(item.tel) }}
              </div>
              <div>
                {{ item.province }}--- {{ item.city }}--- {{ item.county }}---
                {{ item.addressDetail }}--- {{ item.areaCode }}
              </div>
              <div v-if="item.isDefault" style="color: blue">默认地址</div>
              <router-link
                :to="{
                  name: 'dizhi',
                  query: item,
                }"
                style="color: #000"
                >编辑</router-link
              >
            </div>
            <template #right>
              <van-button
                square
                @click="del(index)"
                type="danger"
                text="删除"
                style="height: 100%"
              />
            </template>
          </van-swipe-cell>
        </van-list>
      </div>
    </van-pull-refresh>
  </div>
</template>

<script>
import { mapActions, mapState } from "vuex";
import { ref } from "vue";
export default {
  setup() {
    var loading = ref(false);
    const loading2 = ref(false);
    const finished = ref(false);
    var page = ref(1);
    var size = ref(10);
    return {
      loading,
      finished,
      loading2,
      page,
      size,
    };
  },
  methods: {
    ...mapActions("addr", ["getlist2"]),
    namecode(name) {
      var stat = name.slice(0, 1);
      var end = name.slice(2, 3);
      return `${stat}*${end}`;
    },
    telcode(tel) {
      var stat = tel.slice(0, 3);
      var end = tel.slice(7, 11);
      return `${stat}****${end}`;
    },
    onLoad() {
      if (this.list.length == this.listData.length) {
        this.finished = true;
      } else {
        setTimeout(() => {
          this.page++;
          this.loading2 = false;
        }, 1000);
      }
    },
    onRefresh() {
      setTimeout(() => {
        this.loading = false;
        this.getlist2();
      }, 1000);
    },
    del(index) {
      if (confirm("确定删除吗")) {
        this.list.splice(index, 1);
      }
    },
  },
  computed: {
    ...mapState("addr", ["addr"]),
    listData: function() {
      return this.addr.slice(0, this.page * this.size);
    },
  },
  mounted() {
    this.getlist2();
  },
};
</script>

<style>
.a1 {
  width: 100%;
  height: 150px;
  border: 1px solid #000;
  margin: 5px 0;
}
</style>


// Verify using getKey callback
// Example uses https://github.com/auth0/node-jwks-rsa as a way to fetch the keys.
// dizhi
<template>
  <div>
    <h3>{{type==1?'地址新增':"地址编辑"}}</h3>
     <van-address-edit
     :address-info="info"
   :area-list="areaList"
   show-set-default
  :area-columns-placeholder="['请选择', '请选择', '请选择']"
  @save="onSave"
/>

  </div>
</template>

<script>
import {ref} from 'vue'
import {useRoute,useRouter} from 'vue-router'
import { areaList } from '@vant/area-data';
import {add,edit} from '@/utils/api'
export default {
  setup() {
    var route=useRoute()
    var router=useRouter()
    var info=ref(route.query)
    var type=ref(1)
    if(type.value.id){
         type.value=2
    }
    if(info.isDefault==true)
          {
            info.isDefault=true
          }
          else{
            info.isDefault=false
          }
    var onSave=async(values)=>{
         var res;
         if(type.value==2)
         {
              res=await edit(values)
         }
         else{
             res=await add(values)
         }
         alert(res.data.msg);
         router.push('/home')
    }
    return { 
        areaList,
        type,
        onSave,
        info
     };
  },
};
</script>

<style>

</style>

jwt.decode(token , options)

(Synchronous) Returns the decoded payload without verifying if the signature is valid.

Warning: This will not verify whether the signature is valid. You should not use this for untrusted messages. You most likely want to use jwt.verify instead.

Warning: When the token comes from an untrusted source (e.g. user input or external request), the returned decoded payload should be treated like any other user input; please make sure to sanitize and only work with properties that are expected

token is the JsonWebToken string

options:

  • json: force JSON.parse on the payload even if the header doesn't contain "typ":"JWT".
  • complete: return an object with the decoded payload and header.

Example

// get the decoded payload ignoring signature, no secretOrPrivateKey needed
var decoded = jwt.decode(token);

// get the decoded payload and header
var decoded = jwt.decode(token, {complete: true});
console.log(decoded.header);
console.log(decoded.payload)

Errors & Codes

Possible thrown errors during verification. Error is the first argument of the verification callback.

TokenExpiredError

Thrown error if the token is expired.

Error object:

  • name: 'TokenExpiredError'
  • message: 'jwt expired'
  • expiredAt: ExpDate
jwt.verify(token, 'shhhhh', function(err, decoded) {
  if (err) {
    /*
      err = {
        name: 'TokenExpiredError',
        message: 'jwt expired',
        expiredAt: 1408621000
      }
    */
  }
});

JsonWebTokenError

Error object:

  • name: 'JsonWebTokenError'
  • message:
    • 'invalid token' - the header or payload could not be parsed
    • 'jwt malformed' - the token does not have three components (delimited by a .)
    • 'jwt signature is required'
    • 'invalid signature'
    • 'jwt audience invalid. expected: OPTIONS AUDIENCE'
    • 'jwt issuer invalid. expected: OPTIONS ISSUER'
    • 'jwt id invalid. expected: OPTIONS JWT ID'
    • 'jwt subject invalid. expected: OPTIONS SUBJECT'
jwt.verify(token, 'shhhhh', function(err, decoded) {
  if (err) {
    /*
      err = {
        name: 'JsonWebTokenError',
        message: 'jwt malformed'
      }
    */
  }
});

NotBeforeError

Thrown if current time is before the nbf claim.

Error object:

  • name: 'NotBeforeError'
  • message: 'jwt not active'
  • date: 2018-10-04T16:10:44.000Z
jwt.verify(token, 'shhhhh', function(err, decoded) {
  if (err) {
    /*
      err = {
        name: 'NotBeforeError',
        message: 'jwt not active',
        date: 2018-10-04T16:10:44.000Z
      }
    */
  }
});

Algorithms supported

Array of supported algorithms. The following algorithms are currently supported.

alg Parameter ValueDigital Signature or MAC Algorithm
HS256HMAC using SHA-256 hash algorithm
HS384HMAC using SHA-384 hash algorithm
HS512HMAC using SHA-512 hash algorithm
RS256RSASSA-PKCS1-v1_5 using SHA-256 hash algorithm
RS384RSASSA-PKCS1-v1_5 using SHA-384 hash algorithm
RS512RSASSA-PKCS1-v1_5 using SHA-512 hash algorithm
PS256RSASSA-PSS using SHA-256 hash algorithm (only node ^6.12.0 OR >=8.0.0)
PS384RSASSA-PSS using SHA-384 hash algorithm (only node ^6.12.0 OR >=8.0.0)
PS512RSASSA-PSS using SHA-512 hash algorithm (only node ^6.12.0 OR >=8.0.0)
ES256ECDSA using P-256 curve and SHA-256 hash algorithm
ES384ECDSA using P-384 curve and SHA-384 hash algorithm
ES512ECDSA using P-521 curve and SHA-512 hash algorithm
noneNo digital signature or MAC value included

Refreshing JWTs

First of all, we recommend you to think carefully if auto-refreshing a JWT will not introduce any vulnerability in your system.

We are not comfortable including this as part of the library, however, you can take a look at this example to show how this could be accomplished. Apart from that example there are an issue and a pull request to get more knowledge about this topic.

TODO

  • X.509 certificate chain is not checked

Issue Reporting

If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.

Author

Auth0

License

This project is licensed under the MIT license. See the LICENSE file for more info.