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进行增强
参考文献:
插件的基本语法:插件 - NuxtJS | Nuxt.js 中文网
nuxt拦截器编写:Extending axios - Axios Module
(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')
}
})
}