前端代码:https://github.com/Snowstorm0/token-login-vue
后端代码:https://github.com/Snowstorm0/token-login-spring
使用 Spring+Vue 实现 token 登录、退出、访问拦截等功能。
打开cmd,输入ui命令:
vue ui
若没有反应,可能是版本太低,需要卸载后重装:
npm uninstall vue-cli -g #卸载
npm install @vue/cli -g #安装
执行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
打开cmd,输入ui命令:
vue ui
在插件项搜索,并点击安装。
vue2.0 选择安装 “vue-cli-plugin-element”;vue3.0 选择安装 “vue-cli-plugin-element-plus”。
Terminal安装axios,每个新项目都需要安装:
# vue-cli2.0命令
npm install axios
# vue-cli3.0命令
npm add axios
src/app.vue:
<template>
<div id="app">
<el-container style="height: 500px; border: 1px solid #eee">
<!-- 头部文字 -->
<el-container>
<el-header style="text-align: right; font-size: 18px">
<span>公众号:代码的路</span>
</el-header>
<br><br>
<router-view></router-view>
</el-container>
</el-container>
</div>
</template>
<style>
/* 顶栏 */
.el-header {
background-color: #B3C0D1;
color: #333;
text-align: center;
line-height: 60px;
}
/* 底栏 */
.el-footer {
background-color: #B3C0D1;
color: #333;
text-align: center;
line-height: 60px;
}
/* 侧栏 */
.el-aside {
background-color: #D3DCE6;
color: #333;
text-align: center;
line-height: 200px;
}
/* 主要区域 */
.el-main {
background-color: #E9EEF3;
color: #333;
text-align: center;
}
body > .el-container {
margin-bottom: 40px;
}
</style>
<script>
export default {
data() {
const item = {
};
return {
tableData: Array(20).fill(item)
}
}
};
</script>
src/views/login.vue
<template>
<div class="loginbBody">
<div class="loginDiv">
<div class="login-content">
<h1 class="login-title">用户登录</h1>
<el-form :model="loginForm" label-width="100px"
:rules="rules" ref="loginForm">
<el-form-item label="编号" prop="userId">
<el-input style="width: 200px" type="text" v-model="loginForm.userId"
autocomplete="off" size="small"></el-input>
</el-form-item>
<el-form-item label="密码" prop="password">
<el-input style="width: 200px" type="password" v-model="loginForm.password"
show-password autocomplete="off" size="small"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="confirm">确 定</el-button>
</el-form-item>
</el-form>
</div>
</div>
</div>
</template>
<script>
export default {
name: "login",
data(){
return{
loginForm:{
userId:'',
password:''
},
// 输入信息长度验证
rules:{
userId: [
{ required: true, message: '请输入用户编号', trigger: 'blur' },
{ min: 2, max: 5, message: '用户名长度在 2 到 5 个字符', trigger: 'blur' }
],
password: [
{ required: true, message: '请输密码', trigger: 'blur' },
{ min: 2, max: 5, message: '密码长度在 2 到 5 个字符', trigger: 'blur' }
]
}
}
},
methods:{
// 登录后跳转到主页
confirm(){
this.$refs.loginForm.validate((valid) => {
if (valid) { //valid成功为true,失败为false
//去后台验证用户名密码,并返回token
this.$axios.post('http://localhost:8081/homepage/login',this.loginForm).then(res=>{
console.log(res.data)
if(res.data.code==200){
//存储userId和token到本地
this.$store.commit("setUserId", res.data.userId);
this.$store.commit("setToken", res.data.token);
//跳转到主页
this.$router.replace('/home');
}else{
alert('用户名或密码错误!');
return false;
}
});
} else {
console.log('校验失败');
return false;
}
});
}
}
}
</script>
<style scoped >
.loginbBody {
width: 100%;
height: 100%;
background-color: #B3C0D1;
}
.loginDiv {
position: absolute;
top: 50%;
left: 50%;
margin-top: -200px;
margin-left: -250px;
width: 450px;
height: 330px;
background: #fff;
border-radius: 5%;
}
.login-title {
margin: 20px 0;
text-align: center;
}
.login-content {
width: 400px;
height: 250px;
position: absolute;
top: 25px;
left: 25px;
}
</style>
src/views/HomePage.vue:
<template>
<header>
<div>
<h1 style="margin-top: -10px;color: #425049;font-size:30px; ">代码的路测试页面: vue主页</h1>
</div>
<div class="opt-wrapper">
<el-dropdown :hide-on-click="false">
<div class="demo-basic--circle">
<div class="block">
<el-avatar :size="40" :src="avatar" :class="['avatar-info']">
</el-avatar>
</div>
</div>
<!-- 头像下拉列表 -->
<el-dropdown-menu slot="dropdown" style="margin-top:-30px;margin-left: -40px;">
<el-dropdown-item @click.native="personal"><i class="el-icon-info"></i>个人中心</el-dropdown-item>
<el-dropdown-item @click.native="logout"><i class="el-icon-switch-button"></i>退出登录</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
</div>
</header>
</template>
<script>
export default {
name: "personal",
name: "logout",
data() {
return {
avatar: require('../assets/CodePath.jpg')
}
},
methods:{
personal(){
//跳转到登录路由
this.$router.push({ path: '/personal' })
},
logout(){
//清理数据
this.$store.commit('resetState');
//跳转到登录路由
this.$router.push({ path: '/login' })
},
}
}
</script>
<style scoped>
header {
display: flex;
align-items: center;
justify-content: space-between;
color: #fff;
}
/*设定头像图片样式*/
.avatar-info {
margin-top: 10px;
margin-right: 40px;
cursor: pointer;
}
</style>
src/views/personal.vue:
<template>
<div>
<table>
<tr>
<td>编号</td>
<td>姓名</td>
</tr>
<tr v-for="user in users" :key="user">
<td>{{user.userId}}</td>
<td>{{user.username}}</td>
</tr>
</table>
</div>
</template>
<script>
export default {
name: "personal",
data(){
return {
users:[
],
loginForm:{
userId:'',
password:''
},
}
},
created() {
var that=this;
this.$axios.post('http://localhost:8081/homepage/personal',this.loginForm).then(res=>{
console.log(res.data)
that.users=res.data;
});
}
}
</script>
<style scoped>
</style>
在 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: {
}
})
路由设置是为了在前端进行登录拦截,就是就只有当用户完成登录后才可以访问其他的界面,没有登录之前无法访问,就算用户在地址栏进行输入地址也会直接返回登录界面。
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();
}
})
通过后端生成token,并进行登录拦截。
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;
}
}
即使端口相同,也会出现如下报错:
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);
}
}
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);
}
}
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;
}
}
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;
}
}
}
浏览器打开: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 被清空:
退出后,如果直接在浏览器输入主页面地址(http://localhost:8080/#/home),会被强制跳转回登录页面。
退出后,如果直接在浏览器输入访问后端的地址(http://localhost:8081/homepage/login),会提示认证失败。