vue项目登录及token验证 vue-ant

深碍√TFBOYSˉ_ 2021-07-24 19:29 524阅读 0赞

在前后端完全分离的情况下,Vue项目中实现token验证大致思路如下:

1、第一次登录的时候,前端调后端的登陆接口,发送用户名和密码

2、后端收到请求,验证用户名和密码,验证成功,就给前端返回一个token

3、前端拿到token,将token存储到localStorage和vuex中,并跳转路由页面

4、前端每次跳转路由,就判断 localStroage 中有无 token ,没有就跳转到登录页面,有则跳转到对应路由页面

5、每次调后端接口,都要在请求头中加token

6、后端判断请求头中有无token,有token,就拿到token并验证token,验证成功就返回数据,验证失败(例如:token过期)就返回401,请求头中没有token也返回401

7、如果前端拿到状态码为401,就清除token信息并跳转到登录页面

.
.
.
.
实操代码:

1.login页(账号密码登录完成后,将后台返回的token储存到本地);最后附上了登录页完整代码

  1. handleSubmit(e) {
  2. var that = this;
  3. this.userName = this.userName.trim();
  4. this.password = this.password.trim();
  5. if (this.userName === "" && this.password === "") {
  6. that.$message.warning("账号和密码无内容");
  7. return;
  8. }
  9. if (this.userName === "") {
  10. that.$message.warning("账号无内容");
  11. return;
  12. }
  13. if (this.password === "") {
  14. that.$message.warning("密码无内容");
  15. return;
  16. }
  17. var username = document.getElementById("username").value;
  18. var password = document.getElementById("password").value;
  19. e.preventDefault();
  20. this.form.validateFields((err, values) => {
  21. //这一步将用户名储存在vuex ||||||||||目前域账号和用户名都是写一样了||||||||||||||||||||||||||||||||||||||||||||||||
  22. axios
  23. .post(this.$store.state.windowCONTENT + "sysConfig/getUserRole", {
  24. loginUser: this.userName,
  25. })
  26. .then((res) => {
  27. if (res.data.success == 0) {
  28. //有权限
  29. this.$store.state.loginUser = this.userName;
  30. this.$store.state.userName = this.userName;
  31. this.$store.state.roleCode = res.data.data.roleCode;
  32. //存入token
  33. localStorage.setItem("token",JSON.stringify(res.data.data.token));
  34. // console.log(res.data.data,this.$store.state.roleCode);
  35. if (!err) {
  36. this.$router.push("/layout");
  37. this.$message.success("登陆成功");
  38. }
  39. } else {
  40. //无权限
  41. this.$message.error(res.data.data);
  42. }
  43. });
  44. });
  45. },

2.marn.js(配置请求拦截器,每次请求携带token,后端进行验证;配置响应拦截器,根据后端验证返回的结果,判断token是否过期)

  1. import "babel-polyfill";
  2. import Vue from "vue";
  3. import App from "./App.vue";
  4. import router from "./router";
  5. import store from "./store";
  6. import { Button, message } from 'ant-design-vue';
  7. import Antd from "ant-design-vue";
  8. import "ant-design-vue/dist/antd.css";
  9. import zh_CN from "ant-design-vue/lib/locale-provider/zh_CN";
  10. import moment from "moment";
  11. import "moment/locale/zh-cn";
  12. import "./assets/iconfont/iconfont";
  13. import axios from "axios";
  14. Vue.component(Button.name, Button);
  15. Vue.config.productionTip = false;
  16. Vue.use(Antd);
  17. Vue.prototype.$message = message;
  18. // 设置axios全局默认的BASE-URL, 只要设置了全局的默认base_url,以后的请求会自动拼接上base_url
  19. //axios.defaults.baseURL = 'http://localhost:8888/api/private/v1/'
  20. // 配置axios的请求拦截器-(每次在请求头上携带后台分配的token-后台判断token是否有效等问题)
  21. axios.interceptors.request.use(
  22. function(config) {
  23. // 在发送请求之前做些什么
  24. // console.log('请求到了哟', config.headers.Authorization)
  25. // 统一的给config设置 token
  26. config.headers.Authorization = JSON.parse(localStorage.getItem("token"));
  27. config.headers['Token'] = JSON.parse(localStorage.getItem("token"));
  28. return config;
  29. },
  30. function(error) {
  31. // 对请求错误做些什么
  32. return Promise.reject(error);
  33. }
  34. );
  35. //响应拦截器 与后端定义状态是100时候是错误 跳转到登录界面
  36. axios.interceptors.response.use(function (response) {
  37. // 对响应数据做点什么
  38. console.log(response)
  39. //当返回信息为未登录或者登录失效的时候重定向为登录页面
  40. if (response.data.status == 100 || response.data.message == '用户未登录或登录超时,请登录!') {
  41. router.push({
  42. path: "/login",
  43. querry: { redirect: router.currentRoute.fullPath }//从哪个页面跳转
  44. })
  45. message.warning(response.data.message);
  46. }
  47. return response;
  48. }, function (error) {
  49. // 对响应错误做点什么
  50. return Promise.reject(error)
  51. })
  52. moment.locale("zh-cn");
  53. new Vue({
  54. zh_CN,
  55. router,
  56. watch: {
  57. // 监听路由变化
  58. "$route.path": function(newVal, oldVal) {
  59. console.log(`new_path = ${ newVal}, old_path = ${ oldVal}`);
  60. },
  61. },
  62. store,
  63. render: (h) => h(App),
  64. }).$mount("#app");

3.router.js(配置导航守卫,有token或者是去登录页就通过,否则定向到登录页)

  1. import Vue from 'vue'
  2. import VueRouter from 'vue-router'
  3. import Home from '../views/Home.vue'
  4. import Layout from '../components/Layout.vue'
  5. import Login from '../components/Login.vue'
  6. Vue.use(VueRouter)
  7. const routes = [
  8. {
  9. path: '/',
  10. redirect: 'login'
  11. },
  12. {
  13. path: '/login',
  14. name: 'Login',
  15. component: Login
  16. },
  17. {
  18. path: '/layout',
  19. name: 'Layout',
  20. component: Layout
  21. },
  22. {
  23. path: '/about',
  24. name: 'About',
  25. // route level code-splitting
  26. // this generates a separate chunk (about.[hash].js) for this route
  27. // which is lazy-loaded when the route is visited.
  28. component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  29. }
  30. ]
  31. const router = new VueRouter({
  32. routes
  33. })
  34. // to 到哪去
  35. // from 从哪来
  36. // next 是否放行 next() 放行 next('/login') 拦截到登录
  37. // 如果准备去登录, 不需要拦截
  38. // 如果已经登录过了, 有token, 不需要拦截
  39. // 如果不是去登陆, 且没有 token, 拦截到登录页
  40. router.beforeEach((to, from, next) => {
  41. const token = JSON.parse(localStorage.getItem('token'));
  42. console.log(token);
  43. // console.log(to)
  44. if (to.path === '/login' || token) {
  45. next()
  46. } else {
  47. next('/login')
  48. }
  49. })
  50. export default router

4.退出:清除本地储存的token

  1. //退出登录
  2. signOut() {
  3. console.log("点击了退出", this.$route.query.sessionId);
  4. localStorage.clear("token");
  5. this.$route.push('/')
  6. //将vuex的数据初始化和清除默认的数据
  7. },

.
.
.
.
.
.

完整登录页

  1. <template>
  2. <div class="login">
  3. <div class="logo">
  4. <img :src="logoUrl" alt />
  5. </div>
  6. <div class="welcome">WELCOME</div>
  7. <div class="platform">欢迎来到XX平台</div>
  8. <div class="box">
  9. <a-form
  10. id="components-form-demo-normal-login"
  11. :form="form"
  12. class="login-form"
  13. @submit.prevent="handleSubmit"
  14. >
  15. <a-form-item>
  16. <div class="l-bor">登录</div>
  17. </a-form-item>
  18. <a-form-item>
  19. <div class="account">账号</div>
  20. </a-form-item>
  21. <a-form-item>
  22. <a-input v-model="userName" allowClear class="user-name" placeholder="请输入">
  23. <!-- v-decorator="[
  24. 'userName',
  25. { rules: [{ required: true, message: '请输入账号名!' }] },
  26. ]"-->
  27. <a-icon slot="prefix" type="user" style="color: rgba(0,0,0,.25)" />
  28. </a-input>
  29. </a-form-item>
  30. <a-form-item>
  31. <div class="p-box">密码</div>
  32. </a-form-item>
  33. <a-form-item>
  34. <!-- <a-input
  35. v-decorator="[
  36. 'password',
  37. { rules: [{ required: true, message: 'Please input your Password!' }] },
  38. ]"
  39. type="password"
  40. placeholder="Password"
  41. >
  42. <a-icon slot="prefix" type="lock" style="color: rgba(0,0,0,.25)" />
  43. </a-input>-->
  44. <a-input-password
  45. v-model="password"
  46. allowClear
  47. class="password"
  48. type="password"
  49. placeholder="请输入"
  50. >
  51. <!-- v-decorator="[
  52. 'password',
  53. { rules: [{ required: true, message: '请输入密码!' }] },
  54. ]"-->
  55. <a-icon slot="prefix" type="lock" style="color: rgba(0,0,0,.25)" />
  56. </a-input-password>
  57. </a-form-item>
  58. <a-form-item>
  59. <!-- <a-checkbox
  60. v-decorator="[
  61. 'remember',
  62. {
  63. valuePropName: 'checked',
  64. initialValue: true,
  65. },
  66. ]"
  67. >Remember me</a-checkbox>-->
  68. <!-- <a class="login-form-forgot" href>Forgot password</a> -->
  69. <a-button
  70. :style="{opacity: (btnFlag ? .5 : 1)}"
  71. type="primary"
  72. html-type="submit"
  73. class="login-form-button"
  74. >
  75. <span
  76. style="width:58px;
  77. height:24px;
  78. font-size:17px;
  79. font-family:PingFang-SC-Light,PingFang-SC;
  80. font-weight:300;
  81. color:rgba(255,255,255,1);
  82. line-height:24px;
  83. text-shadow:0px 2px 3px rgba(62,32,201,0.1);"
  84. >登录</span>
  85. </a-button>
  86. <!-- Or -->
  87. <!-- <a href>register now!</a> -->
  88. </a-form-item>
  89. </a-form>
  90. </div>
  91. <div class="bottom"></div>
  92. </div>
  93. </template>
  94. <script>
  95. import axios from "axios";
  96. export default {
  97. data() {
  98. return {
  99. logoUrl: require("../assets/logo.svg"),
  100. userName: "",
  101. password: "",
  102. btnFlag: true,
  103. flagColor: {
  104. opacity: 0.5,
  105. },
  106. };
  107. },
  108. beforeCreate() {
  109. this.form = this.$form.createForm(this, { name: "normal_login" });
  110. },
  111. created() {
  112. },
  113. methods: {
  114. handleSubmit(e) {
  115. var that = this;
  116. this.userName = this.userName.trim();
  117. this.password = this.password.trim();
  118. if (this.userName === "" && this.password === "") {
  119. that.$message.warning("账号和密码无内容");
  120. return;
  121. }
  122. if (this.userName === "") {
  123. that.$message.warning("账号无内容");
  124. return;
  125. }
  126. if (this.password === "") {
  127. that.$message.warning("密码无内容");
  128. return;
  129. }
  130. // jucenter.submit({name:this.userName,pwd:this.password});
  131. e.preventDefault();
  132. this.form.validateFields((err, values) => {
  133. //这一步将用户名储存在vuex ||||||||||目前域账号和用户名都是写一样了||||||||||||||||||||||||||||||||||||||||||||||||
  134. console.log(this.userName, this.password);
  135. axios.post(
  136. this.$store.state.windowCONTENT + "sysConfig/getUserRole",
  137. { loginUser: this.userName}
  138. ).then(res => {
  139. if (res.data.success == 0) { //有权限
  140. this.$store.state.loginUser = this.loginUser;
  141. this.$store.state.userName = res.data.data.userName;
  142. this.$store.state.roleCode = res.data.data.roleCode;
  143. //存入token
  144. localStorage.setItem("token",JSON.stringify(res.data.data.token));
  145. if (!err) {
  146. this.$router.push("/layout");
  147. console.log(111);
  148. this.$message.success('登陆成功')
  149. }
  150. } else { //无权限
  151. this.$message.error(res.data.data)
  152. }
  153. })
  154. });
  155. },
  156. },
  157. watch: {
  158. userName: function (v1, v2) {
  159. var that = this;
  160. if (v1 && this.password) {
  161. this.btnFlag = false;
  162. console.log(this.btnFlag);
  163. } else {
  164. this.btnFlag = true;
  165. console.log(this.btnFlag);
  166. }
  167. },
  168. password: function (v1, v2) {
  169. var that = this;
  170. if (v1 && this.userName) {
  171. this.btnFlag = false;
  172. console.log(this.btnFlag);
  173. } else {
  174. this.btnFlag = true;
  175. console.log(this.btnFlag);
  176. }
  177. },
  178. },
  179. };
  180. </script>
  181. <style lang="less">
  182. .login {
  183. position: relative;
  184. text-align: left;
  185. height: 100%;
  186. background: linear-gradient(
  187. 154deg,
  188. rgba(119, 182, 244, 1) 0%,
  189. rgba(66, 106, 229, 1) 100%
  190. );
  191. // background-color: pink!important;
  192. // overflow: hidden;
  193. .logo {
  194. position: absolute;
  195. top: 21px;
  196. left: 35px;
  197. }
  198. .welcome {
  199. position: absolute;
  200. bottom: 60%;
  201. left: 10%;
  202. width: 416px;
  203. height: 100px;
  204. font-size: 72px;
  205. font-family: PingFang-SC-Regular, PingFang-SC;
  206. font-weight: 400;
  207. color: rgba(255, 255, 255, 1);
  208. line-height: 100px;
  209. letter-spacing: 6px;
  210. }
  211. .platform {
  212. position: absolute;
  213. bottom: 53%;
  214. left: 10%;
  215. width: 313px;
  216. height: 33px;
  217. font-size: 24px;
  218. font-family: PingFang-SC-Light, PingFang-SC;
  219. font-weight: 300;
  220. color: rgba(255, 255, 255, 1);
  221. line-height: 33px;
  222. letter-spacing: 2px;
  223. }
  224. .box {
  225. position: absolute;
  226. bottom: 10%;
  227. right: 0;
  228. // margin: 0 auto;
  229. // margin-bottom: 151px; //定位高度-----↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
  230. margin-right: 21%;
  231. width: 370px;
  232. height: 500px;
  233. border-radius: 10px;
  234. background: rgba(252, 251, 255, 1);
  235. padding: 0px 53px;
  236. //去除默认下边距
  237. .ant-form-item {
  238. margin-bottom: 0;
  239. }
  240. //输入框
  241. .ant-input-affix-wrapper .ant-input:not(:last-child) {
  242. height: 36px;
  243. font-size: 14px;
  244. font-family: PingFang-SC-Regular, PingFang-SC;
  245. font-weight: 400;
  246. color: rgba(53, 58, 64, 1);
  247. // background-color: pink;
  248. }
  249. //登录按钮
  250. #components-form-demo-normal-login .login-form-button {
  251. width: 264px;
  252. height: 44px;
  253. background: linear-gradient(
  254. 90deg,
  255. rgba(60, 163, 247, 1) 0%,
  256. rgba(28, 106, 235, 1) 100%
  257. );
  258. box-shadow: 0px 2px 3px 0px rgba(62, 32, 201, 0.1);
  259. border-radius: 6px;
  260. }
  261. .l-bor {
  262. margin-left: -53px;
  263. margin-top: 50px;
  264. line-height: 25px;
  265. border-left: 6px solid rgba(28, 106, 235, 1);
  266. padding-left: 47px;
  267. font-size: 18px;
  268. font-family: PingFang-SC-Medium, PingFang-SC;
  269. font-weight: 500;
  270. color: rgba(53, 58, 64, 1);
  271. letter-spacing: 1px;
  272. }
  273. // .account{
  274. // margin-top: 58px;
  275. // width:27px;
  276. // height:17px;
  277. // font-size:12px;
  278. // font-family:PingFang-SC-Light,PingFang-SC;
  279. // font-weight:300;
  280. // color:rgba(53,58,64,1);
  281. // line-height:17px;
  282. // letter-spacing:1px;
  283. // }
  284. .ant-form-item:nth-child(2) {
  285. position: absolute;
  286. top: 133px;
  287. .account {
  288. width: 27px;
  289. height: 17px;
  290. font-size: 12px;
  291. font-family: PingFang-SC-Light, PingFang-SC;
  292. font-weight: 300;
  293. color: rgba(53, 58, 64, 1);
  294. line-height: 17px;
  295. letter-spacing: 1px;
  296. }
  297. }
  298. .ant-form-item:nth-child(3) {
  299. position: absolute;
  300. top: 160px;
  301. width: 264px;
  302. }
  303. .ant-form-item:nth-child(4) {
  304. position: absolute;
  305. top: 230px;
  306. width: 264px;
  307. .p-box {
  308. width: 27px;
  309. height: 17px;
  310. font-size: 12px;
  311. font-family: PingFang-SC-Light, PingFang-SC;
  312. font-weight: 300;
  313. color: rgba(53, 58, 64, 1);
  314. line-height: 17px;
  315. letter-spacing: 1px;
  316. }
  317. }
  318. .ant-form-item:nth-child(5) {
  319. position: absolute;
  320. top: 257px;
  321. width: 264px;
  322. }
  323. .ant-form-item:nth-child(6) {
  324. position: absolute;
  325. top: 376px;
  326. width: 264px;
  327. }
  328. }
  329. .bottom {
  330. position: absolute;
  331. bottom: 0;
  332. width: 100%;
  333. // height: 151px; //固定高度-----↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
  334. height: 10%; //固定高度-----↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
  335. background: linear-gradient(
  336. 360deg,
  337. rgba(75, 118, 232, 0) 0%,
  338. rgba(57, 98, 224, 0.41) 100%
  339. );
  340. }
  341. }
  342. #components-form-demo-normal-login .login-form {
  343. max-width: 300px;
  344. }
  345. #components-form-demo-normal-login .login-form-forgot {
  346. float: right;
  347. }
  348. #components-form-demo-normal-login .login-form-button {
  349. width: 100%;
  350. }
  351. </style>

发表评论

表情:
评论列表 (有 0 条评论,524人围观)

还没有评论,来说两句吧...

相关阅读

    相关 用户登录token验证

    1.场景还原      可能还有很多小伙伴对token概念朦朦胧胧,今天笔者以项目中的用户登录的token验证需求跟大家讲讲其中的来龙去脉,希望能够理清大伙的思路。