共计 11401 个字符,预计需要花费 29 分钟才能阅读完成。
原文链接
前端代码:https://github.com/Snowstorm0…
后端代码:https://github.com/Snowstorm0…
应用 Spring+Vue 实现 token 登录、退出、拜访拦挡等性能。
1 前端
1.1 创立我的项目
关上 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
1.2 装置插件
1.2.1 element-ui
关上 cmd,输出 ui 命令:
vue ui
在插件项搜寻,并点击装置。
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.3 主体代码
1.3.1 App
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>
1.3.2 登录页
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>
1.3.3 主页
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>
1.3.4 集体核心页
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>
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.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();}
})
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;
}
}
2.2 跨域设置
即便端口雷同,也会呈现如下报错:
Access to XMLHttpRequest at ‘http://localhost:8088/admin/l…’ 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);
}
}
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);
}
}
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;
}
}
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;}
}
}
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/homepag…),会提醒认证失败。
学习更多编程常识,请关注我的公众号:
代码的路