SpringSecurity+前端项目+redis完成认证授权的代码

1. 前端准备工作--都在全局main.js页面中设置的

1.1. 创建Vue工程后,并导入element ui和axios,添加连接后端项目的路径,把axios挂载到Vue

1.2. 前置路由守卫(所有路由跳转前核实一下身份)

//前置路由守卫--所有的路由跳转都先经过这里
    // to:即将要访问的路径  from:从哪里来 next:放行函数
  //解决登录之后关闭浏览器之后,还可以不用登录就能进入登录后的页面
  router.beforeEach((to, from, next) => {
    //如果是  登录页面 或者 token为真 就放行    其他情况强制跳转到登录页面
    const token = sessionStorage.getItem('token');
    if (to.path==="/login" || token){
      return next();
    }
    return next("/login");
  })

1.3. 请求过滤器(所有请求前都需携带令牌给后端)

//请求拦截器--每次请求前都会经过的
//这里的意义就是需要每次向后端发送请求都要携带者token令牌
axios.interceptors.request.use(function (config) {
  let token = sessionStorage.getItem('token');

  if (token){
    config.headers.token = token;
  }
  return config;
})

1.4. 响应拦截器(后端响应过来的json数据,根据code状态码判断成功/失败,并返回json数据给对应的请求,这里请求处只需要写对应的操作即可)

//设置响应拦截器
axios.interceptors.response.use(function (response) {
  if (response.data.code===200){
    Vue.prototype.$message.success(response.data.msg)
    return response;
  }else {
    Vue.prototype.$message.error(response.data.msg);
    return response;
  }
})

1.5. 页面布局路由导入跳转和请求

<template>
  <div class="home">
    <h1>主页页面</h1>
    <el-button type="success" @click="add()">增加</el-button>
    <el-button type="danger" @click="del()">删除</el-button>
    <el-button type="info" @click="update()">修改</el-button>
    <el-button type="primary" @click="sel()">查询</el-button>
    <el-button type="warning" @click="exp()">导出</el-button>
    <el-button icon="el-icon-switch-button" @click="outLogin()">退出</el-button>
  </div>
</template>

<script>
export default {
  name: 'home',
  data(){
  return{

  }
  },
  methods:{
    //退出
    outLogin(){
      this.$axios.post("/logout").then((res) => {
        sessionStorage.removeItem("token")
        this.$router.push("/login")
      })
    },
    //添加用户
    add(){
      this.$axios.get("/user/insert").then(res=>{

      })
    },
    //删除用户
    del(){
      this.$axios.get("/user/delete").then(res=>{

      })
    },
    //修改用户
    update(){
      this.$axios.get("/user/update").then(res=>{

      })
    },
    //查询
    sel(){
      this.$axios.get("/user/select").then(res=>{

      })
    },
    //导出
    exp(){
      this.$axios.get("/user/export").then(res=>{

      })
    }
  },
}
</script>
<style>
.home{
  margin: auto;
  text-align: center;
}
</style>

2. 后端准备工作

2.1. JWT工具类,客户端与服务器通信,都要带上jwt,放在http请求的头信息中

2.1.1. 引入jar
<!--引入jwt的依赖-->
<dependency>
  <groupId>com.auth0</groupId>
  <artifactId>java-jwt</artifactId>
  <version>4.4.0</version>
</dependency>
2.1.2. 创建jwt的工具类
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值