• Spring+Vue实现token登录


    原文链接

    前端代码:https://github.com/Snowstorm0/token-login-vue

    后端代码:https://github.com/Snowstorm0/token-login-spring

    使用 Spring+Vue 实现 token 登录、退出、访问拦截等功能。

    1 前端

    1.1 创建项目

    打开cmd,输入ui命令:

    vue ui
    
    • 1

    若没有反应,可能是版本太低,需要卸载后重装:

    npm uninstall vue-cli -g   #卸载
    npm install @vue/cli -g    #安装
    
    • 1
    • 2

    执行ui命令成功后,会出现提示:

    🚀 Starting GUI…
    🌠 Ready on http://localhost:8000

    并会自动打开页面:

    创建名为SpringAndVue-vue的项目,预设选择“手动”;功能开启 Babel、Router、Vuex、Linter/Formatter;配置选择“ESLint with error prevention only”;版本建议使用 “vue2.0”。创建新项目。

    通过cd进入目录,启动项目:

    npm run serve
    
    • 1

    1.2 安装插件

    1.2.1 element-ui

    打开cmd,输入ui命令:

    vue ui
    
    • 1

    在插件项搜索,并点击安装。

    vue2.0 选择安装 “vue-cli-plugin-element”;vue3.0 选择安装 “vue-cli-plugin-element-plus”。

    1.2.2 axios

    Terminal安装axios,每个新项目都需要安装:

    # vue-cli2.0命令
    npm install axios
    # vue-cli3.0命令
    npm add axios
    
    • 1
    • 2
    • 3
    • 4

    1.3 主体代码

    1.3.1 App

    src/app.vue:

    
    
    
    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60

    1.3.2 登录页

    src/views/login.vue

    
    
    
    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111

    1.3.3 主页

    src/views/HomePage.vue:

    
    
    
    
    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65

    1.3.4 个人中心页

    src/views/personal.vue:

    
    
    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    1.3.5 存储设置

    在 JavaScript 中有两个属性:sessionStorage 和 localStorage。这两个属性用法相似,都用于保存数据,sessionStorage 是会话存储,数据保留至关闭当前页面,刷新是不会丢失数据的;localStorage 是本地存储,数据会一直保留,除非手动删除该数据。

    一般来说,sessionStorage 可以用于保存 token,而 localStorage 可以用于记住密码,将密码保留在本地,之后就不用再输入密码了。

    在这里我们为了简化项目,使用 localStorage 存储 token。

    src/store/index.js:

    import Vue from 'vue'
    import Vuex from 'vuex'
    
    Vue.use(Vuex)
    export default new Vuex.Store({
      state: {
        token: '',
        username: '代码的路'
      },
      getters: {
      },
      mutations: {
        setUserId(state, userId){
          state.userId = userId;
          localStorage.setItem("userId",userId);  //存储userId
        },
        setToken(state, token){
          state.token = token;
          localStorage.setItem("token",token);  //存储token
        },
        resetState(state){
          state.userId = '';
          state.token = '';
          localStorage.clear();        //清除token
      }
      },
      actions: {
      },
      modules: {
      }
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    1.3.6 路由拦截

    路由设置是为了在前端进行登录拦截,就是就只有当用户完成登录后才可以访问其他的界面,没有登录之前无法访问,就算用户在地址栏进行输入地址也会直接返回登录界面。

    vue 组件化的开发就是使用 vue-router 进行页面跳转的。我们在定义路由的时候,在meta属性中存放一个属性来判断该路由是否需要检查(如果为true,那就需要检查,在满足条件是才可以跳转到该路由)。

    src/router/index.js:

    import Vue from 'vue'
    import VueRouter from 'vue-router'
    import HomePage from "../views/HomePage";
    import personal from "../views/personal";
    Vue.use(VueRouter)
    const routes = [
    
       {
        path: '/login',
        name: '登录',
        component: () => import(/* webpackChunkName: "user" */ '../views/login.vue')
       },
       {
        path: '/',
        name: '/',
        redirect: '/login',
        //redirect   表示当路径使用到‘/’是,就自动跳转到路径为‘/login’
      },
      {
        path: '/home',
        name: 'home',
        component: HomePage,
        meta: {
          requireAuth: true // 添加该字段,表示进入这个路由是需要登录的
          },
      },
      {
        path: '/personal',
        name: 'personal',
        component: personal,
        meta: {
          requireAuth: true // 添加该字段,表示进入这个路由是需要登录的
          },
      },
    ]
    const router = new VueRouter({
      routes
    })
    
    export default router
    
    //登录拦截
    router.beforeEach((to, from, next) => {
      if (to.meta.requireAuth) {  // 如果被拦截
          
          if (localStorage.token) {  //如果有token
              next();
          }
          else {      //如果无token              
              next({
                  path: '/login',//返回登录界面
              })
              }
      }
      else {     //如果不被拦截
          next();
      }
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58

    2 后端

    通过后端生成token,并进行登录拦截。

    2.1 controller层

    MyController.java

    @RestController
    @RequestMapping("/homepage")
    public class MyController {
    
        // 登录
        @PostMapping("/login")
        public resultMap toLogin(@RequestBody User user){
            // 数据应从数据库读取,此处简化
            String userId = "admin";
            String password = "admin";
            String token=null;
            // 若密码正确,生成token
            if(user!=null && user.getUserId().equals(userId) && user.getPassword().equals(password)){
                token = TokenUtil.sign(user);
            }
    
            resultMap res;
            if(token == null){
                res = new resultMap(400,userId,"登录失败,请重试");
            }else{
                res = new resultMap(200,userId,token);
            }
            System.out.println("user:" + user);
            System.out.println("token:" + token);
            return res;
        }
        // 个人中心
        @PostMapping("/personal")
        public List<User> Personal(@RequestBody User obj){
    
            // 数据应从数据库读取,此处简化
            User user = new User();
            user.setUserId("123");
            user.setUsername("代码的路");
    
            List<User> res = new ArrayList<>();
            res.add(user);
            System.out.println("res:" + res);
            return res;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    2.2 跨域设置

    即使端口相同,也会出现如下报错:

    Access to XMLHttpRequest at ‘http://localhost:8088/admin/login’ from origin ‘http://localhost:8080’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

    所以需要解决跨域问题。

    common/Config.java:

    @Configuration
    public class Config {
        @Bean
        public CorsFilter corsFilter() {
            final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
            final CorsConfiguration corsConfiguration = new CorsConfiguration();
            /*是否允许请求带有验证信息*/
            corsConfiguration.setAllowCredentials(true);
            /*允许访问的客户端域名*/
            corsConfiguration.addAllowedOrigin("*");
            /*允许服务端访问的客户端请求头*/
            corsConfiguration.addAllowedHeader("*");
            /*允许访问的方法名,GET POST等*/
            corsConfiguration.addAllowedMethod("*");
            urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
            return new CorsFilter(urlBasedCorsConfigurationSource);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    2.3 配置token拦截器

    jwt/IntercepterConfig.java:

    @Configuration
    public class IntercepterConfig implements WebMvcConfigurer {
        private TokenInterceptor tokenInterceptor;
        //构造方法
        public IntercepterConfig(TokenInterceptor tokenInterceptor){
            this.tokenInterceptor = tokenInterceptor;
        }
        @Override
        public void addInterceptors(InterceptorRegistry registry){
            List<String> excludePath = new ArrayList<>();
            excludePath.add("/homepage/login"); // 登录页面不进行拦截
    //        excludePath.add("/homepage/logout"); // 登出
            registry.addInterceptor(tokenInterceptor)
                    .addPathPatterns("/**")
                    .excludePathPatterns(excludePath);
            WebMvcConfigurer.super.addInterceptors(registry);
        }
    	// 跨域支持
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("*")
                    .allowCredentials(true)
                    .allowedMethods("GET", "POST", "DELETE", "PUT", "PATCH", "OPTIONS", "HEAD")
                    .maxAge(3600 * 24);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    2.4 token拦截器进行拦截

    jwt/TokenInterceptor:

    @Component
    public class TokenInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler)throws Exception{
            if(request.getMethod().equals("OPTIONS")){
                response.setStatus(HttpServletResponse.SC_OK);
                return true;
            }
            response.setCharacterEncoding("utf-8");
            String token = request.getHeader("token");
            System.out.println("intercept token:" + token);
            if(token != null){       // token非空
                boolean result = TokenUtil.verify(token);   // token正确
                if(result){
                    System.out.println("通过拦截器");
                    return true;
                }
            }
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = null;
            try{
                JSONObject json = new JSONObject();
                json.put("success","false");
                json.put("msg","认证失败,未通过拦截器");
                json.put("code","99999");
                response.getWriter().append(json.toJSONString());
                System.out.println("认证失败,未通过拦截器");
            }catch (Exception e){
                e.printStackTrace();
                response.sendError(500);
                return false;
            }
            return false;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    2.5 签名生成和认证

    public class TokenUtil {
        private static final long EXPIRE_TIME= 15*60*1000;
        private static final String TOKEN_SECRET="password";  //密钥盐
        // 签名生成
        public static String sign(User user){
            String token = null;
            try {
                Date expiresAt = new Date(System.currentTimeMillis() + EXPIRE_TIME);
                token = JWT.create()
                        .withIssuer("auth0")
                        .withClaim("userId", user.getUserId())
                        .withExpiresAt(expiresAt)
                        // 使用了HMAC256加密算法。
                        .sign(Algorithm.HMAC256(TOKEN_SECRET));
            } catch (Exception e){
                e.printStackTrace();
            }
            return token;
        }
        // 签名验证
        public static boolean verify(String token){
            try {
                JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build();
                DecodedJWT jwt = verifier.verify(token);
                System.out.println("认证通过:");
                System.out.println("issuer: " + jwt.getIssuer());
                System.out.println("userId: " + jwt.getClaim("userId").asString());
                System.out.println("过期时间:" + jwt.getExpiresAt());
                return true;
            } catch (Exception e){
                return false;
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    3 效果

    3.1 正常登陆

    浏览器打开:http://localhost:8080/#/login

    使用F12进行查看。

    在没登录之前,可以看到 Local Storage 为空:

    登陆以后,跳转到主页面:http://localhost:8080/#/home

    可以看到 Local Storage 存储了生成的 userId 和 token。

    鼠标移动到头像处,点击个人中心:

    跳转到个人中心页面:http://localhost:8080/#/personal

    看到如下内容:

    退回主页面http://localhost:8080/#/home,鼠标移动到头像处,点击退出登录,回到登录页面,此时 Local Storage 被清空:

    3.2 前端拦截

    退出后,如果直接在浏览器输入主页面地址(http://localhost:8080/#/home),会被强制跳转回登录页面。

    3.3 后端拦截

    退出后,如果直接在浏览器输入访问后端的地址(http://localhost:8081/homepage/login),会提示认证失败。

     
     

    学习更多编程知识,请关注我的公众号:

    代码的路

  • 相关阅读:
    shell脚本--------函数
    java计算机毕业设计疫情防控期间人员档案追演示录像上源码+系统+mysql数据库+lw文档
    虚拟DOM与diff算法
    协议-TCP协议-基础概念01-TCP头格式-TCP连接状态图-三次握手和四次挥手
    一文读懂苹果的差分隐私技术原理
    LeetCode 每日一题 2023/8/28-2023/9/3
    分布式存储系统之Ceph集群状态获取及ceph配置文件说明
    YUM安装httpd实验配置apache
    【蓝桥杯选拔赛真题48】Scratch购物程序 少儿编程scratch蓝桥杯选拔赛真题讲解
    第十四届蓝桥杯模拟赛(第二期)
  • 原文地址:https://blog.csdn.net/zbzcDZF/article/details/126537936