[JWT微服务]整合登录-登录服务:生成token

1.用户服务JWT环境

(1)pom文件

(2)工具类

(3)配置yml文件

2.配置类:用于加载自定yml配置内容

package com.czxy.config;

import com.czxy.utils.RsaUtils;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;


@Data
@ConfigurationProperties(prefix = "sc.jwt")
@Component
public class JwtProperties {
    private String secret; // 密钥

    private String pubKeyPath;// 公钥

    private String priKeyPath;// 私钥

    private int expire;// token过期时间

    private PublicKey publicKey; // 公钥

    private PrivateKey privateKey; // 私钥

    @PostConstruct			//当前类加载到spring容器时,执行(初始化操作)
    public void init(){
        try {
            File pubFile = new File(this.pubKeyPath);
            File priFile = new File(this.priKeyPath);
            if( !pubFile.exists() || !priFile.exists()){
                RsaUtils.generateKey( this.pubKeyPath ,this.priKeyPath , this.secret);
            }
            this.publicKey = RsaUtils.getPublicKey( this.pubKeyPath );
            this.privateKey = RsaUtils.getPrivateKey( this.priKeyPath );
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

(1)生成token

  @Resource
    private JwtProperties jwtProperties;

    @PostMapping("/login")
    public BaseResult<User> login(@RequestBody User user) {
        //2 登录
        User loginUser = userService.login(user.getUserName(), user.getPassword());
        //3 处理结果
        if(loginUser != null) {
            // 登录成功
            /*
            BaseResult baseResult = new BaseResult();
            baseResult.setCode(20000);
            baseResult.setMessage("登录成功");
            baseResult.getOther().put("loginUser",loginUser);
             */
            //生成token
            String token = JwtUtils.generateToken(loginUser, jwtProperties.getExpire(), jwtProperties.getPrivateKey());


            return BaseResult.ok("登录成功").append("loginUser",loginUser).append("token", token);
        } else {
            // 失败
            return BaseResult.error("用户名或密码不匹配!!!");
        }
    }

3.前端保存/携带token

  • 保存:登录成功后,保存到localStorage中

  • 携带:每次Ajax前,都追加token。需要对axios进行增强,底层需要编写axios的请求拦截器。

    • 最终采用nuxt的插件对axios进行增强

  • 参考文献:

(1)浏览器端保存token

(2)nuxt插件:配置插件位置

插件内容:(Extending axios - Axios Module

export default function ({ $axios, redirect }) {
    //请求前执行(请求拦截器)
    $axios.onRequest(config => {
        //获得token
        let token = localStorage.getItem('token')
        //携带token
        $axios.setToken(token)
    })
  
    //Ajax请求失败时执行
    $axios.onError(error => {
      const code = parseInt(error.response && error.response.status)
      if (code === 400) {
        redirect('/400')
      }
    })
  }
  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值