Vue整合JWT实现用户登录----权限校验

  • 步骤详解

    • 功能一 : 登录成功后使用jwt生成随机码,并传递给浏览器(token)
    • 功能二 : 浏览器判断登录成功后,把token保存到sessionStorage中(会话级别)
    • 功能三 : 在每次发送http请求时都加上一个请求头Authorization___请求拦截器
    • 功能四 : zuul过滤器中进行拦截判断
      • 判断是否访问登录服务
      • 进行token校验
    • 功能五 : 使用响应拦截器进行拦截判断状态码,跳转login页面
  • 步骤实现

    • 功能一 : 登录成功后使用jwt生成随机码,并传递给浏览器(token)

      package com.czxy.service.impl;
      
      import com.czxy.domain.User;
      import com.czxy.mapper.UserMapper;
      import com.czxy.service.UserService;
      import com.czxy.utils.JwtUtils;
      import com.czxy.utils.RasUtils;
      import com.czxy.vo.BaseResult;
      import org.springframework.stereotype.Service;
      import org.springframework.transaction.annotation.Transactional;
      import tk.mybatis.mapper.entity.Example;
      
      import javax.annotation.Resource;
      
      /**
       * @Author Pole丶逐
       * @Date 2019/12/21 10:36
       * @E-mail
       */
      @Service
      @Transactional
      public class UserServiceImpl implements UserService {
          @Resource
          private UserMapper userMapper;
      
          @Override
          public BaseResult login(User user) throws Exception {
              Example example = new Example(User.class);
              Example.Criteria c = example.createCriteria();
              c.andEqualTo("userName",user.getUserName());
              c.andEqualTo("password",user.getPassword());
              User loginUser = userMapper.selectOneByExample(example);
              if (loginUser == null){
                  return BaseResult.error("用户名或密码错误");
              }
              //Jwt生成随机码
              String token = JwtUtils.generateToken(loginUser, 30, RasUtils.getPrivateKey(RasUtils.priKeyPath));
              return BaseResult.ok("登录成功").append("token",token);
          }
      }
      
    • 功能二 : 浏览器判断登录成功后,把token保存到sessionStorage中(会话级别)

    <script>
    import {login} from '../api'
    export default {
        data() {
            return {
                loginUser : {}
            }
        },
        methods: {
            async loginFn(){
                let {data : dataResult} = await login(this.loginUser)
                if (dataResult.code == 1) {
                    this.$message.success(dataResult.message)
                    //包token保存到sessionStorage中
                    sessionStorage.setItem('token',dataResult.other.token)
                    this.$router.push('/classesAdd')
                }else{
                    this.$message.error(dataResult.message)
                }
            }
        },
    }
    </script>
    
    • 功能三 : 在每次发送http请求时都加上一个请求头Authorization___请求拦截器(api.js)

      //请求拦截器,加入请求头
      axios.interceptors.request.use(request => {
          // Do something before request is sent
          let token = sessionStorage.getItem('token')
       
          if (token) {
              request.headers.Authorization = token
          }
          return request;
      }, error => {
          // Do something with request error
          return Promise.reject(error);
      });
      
    • 功能四 : zuul过滤器中进行拦截判断

      • 判断是否访问登录服务

      • 进行token校验

        package com.czxy.filter;
        
        import com.czxy.domain.User;
        import com.czxy.utils.JwtUtils;
        import com.czxy.utils.RasUtils;
        import com.netflix.zuul.ZuulFilter;
        import com.netflix.zuul.context.RequestContext;
        import com.netflix.zuul.exception.ZuulException;
        import org.springframework.stereotype.Component;
        
        import javax.servlet.http.HttpServletRequest;
        
        /**
         * @Author Pole丶逐
         * @Date 2019/12/22 13:21
         * @E-mail
         */
        @Component
        public class LoginFilter extends ZuulFilter {
            @Override
            public String filterType() {
                return "pre";
            }
        
            @Override
            public int filterOrder() {
                return 1;
            }
        
            @Override
            public boolean shouldFilter() {
                RequestContext requestContext = RequestContext.getCurrentContext();
                HttpServletRequest request = requestContext.getRequest();
                String uri = request.getRequestURI();
                System.out.println(uri);
                if (uri.equals("/xma/client/user/login")){
                    return false;
                }
                return true;
            }
        
            @Override
            public Object run() throws ZuulException {
                RequestContext requestContext = RequestContext.getCurrentContext();
                HttpServletRequest request = requestContext.getRequest();
                String token = request.getHeader("Authorization");
                try {
                    JwtUtils.getObjectFromToken(token, RasUtils.getPublicKey(RasUtils.pubKeyPath), User.class);
                } catch (Exception e) {
                    requestContext.setSendZuulResponse(false);
                    requestContext.setResponseStatusCode(403);
                }
                return null;
            }
        }
        
    • 功能五 : 使用响应拦截器进行拦截判断状态码,跳转login页面(api.js)

      //必须先进行router的导入,否则无法进行跳转
      import router from './router'
      
      //响应拦截器,判断状态码
      axios.interceptors.response.use(response => {
          // Do something before response is sent
          return response;
      }, error => {
          // Do something with response error
          if(error.response.status == 403){
              router.push('/login')
          } 
          return Promise.reject(error);
      });
      
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值