当前位置: 首页 > news >正文

前端和后端权限控制【笔记】

前端权限设置【笔记】

  • 前言
  • 版权
  • 推荐
  • 前端权限设置
    • 需求
    • 效果
    • 实现
    • 资源
  • 后端权限控制
    • 1.给所有前端请求都携带token
    • 2.添加拦截器
    • 3.配置到WebMvcConfiguration
    • 4.更多的权限验证
  • 最后

前言

2024-3-15 18:27:26

以下内容源自《【笔记】》
仅供学习交流使用

版权

禁止其他平台发布时删除以下此话
本文首次发布于CSDN平台
作者是CSDN@日星月云
博客主页是https://jsss-1.blog.csdn.net
禁止其他平台发布时删除以上此话

推荐

前端权限设置

需求

family权限的用户不能访问doctor/*.html

效果

访问doctor/*.html弹出“你不是医生账户”,
重定向到home.html

在这里插入图片描述

实现

获取到当前路径currentURL
获取到当前用户角色userRole
判断这个路径是否是该角色能访问的

function onload(){var currentURL = window.location.href;// console.log("当前页面路径是:" + currentURL);// console.log(userRole);var adminMatch = currentURL.match(/\/admin\//);if (adminMatch&&userRole!='admin'){alertBox("你不是管理员账户",function(){window.location.href="../home.html";});} var doctorMatch = currentURL.match(/\/doctor\//);if (doctorMatch&&userRole!='doctor'){alertBox("你不是医生账户",function(){window.location.href="../home.html";});} var familyMatch = currentURL.match(/\/family\//);if (familyMatch&&userRole!='family') {alertBox("你不是家属账户",function(){window.location.href="../home.html";});} }

资源

模块结构

在这里插入图片描述

具体的user.js实现

调用栈

$(document).ready(function () {set_login_status();{storage(result.data);{onload(userRole);}}
}

每一个页面都有这个的引入

<script src="./js/user.js"></script>
$(document).ready(function () {// 设置用户登录状态set_login_status();// 注销按钮单击事件$("#btn-logout").click(function (e) { logout();        });
});
function set_login_status() {var $A = $(".user-name");if (!$A) return false;$.ajax({type: "GET",url: SERVER_PATH + "/user/status",xhrFields: {withCredentials: true},success: function (result) {if (result.status == "0" && result.data) {$A.text(result.data.nickname);$("#user-info").show();$("#center").show();$("#register").hide();$("#login").hide();window.sessionStorage.setItem("id", result.data.userId);storage(result.data);// 根据用户的 userGroup 来设置跳转路径var centerLink;if (result.data.userGroup === "管理员") {centerLink = "./admin/center.html";} else if (result.data.userGroup === "医生") {centerLink = "./doctor/center.html";} else if(result.data.userGroup === "老人家属"){centerLink = "./family/center.html"; } else {centerLink = "./user/center.html"; // 默认路径}$("#center").attr("href", centerLink); // 设置跳转路径} else {$("#user-info").hide();$("#center").hide();$("#register").show();$("#login").show();}}});    
}
var userRole;//根据用户id查到用户组中返回 account 存入sessionStorage
function storage(user) {var id=user.userId;var token=sessionStorage.getItem("token");$.ajax({type: "GET",url: SERVER_PATH + "/user/account",data: {"userId":id,"token": token},xhrFields: {withCredentials: true},success: function (result) {if (result.status == "0" && result.data) {//存储Accountwindow.sessionStorage.setItem(result.data.type, result.data.account);if(result.data.type=='adminAccount'){userRole='admin';}else if(result.data.type=='doctorAccount'){userRole='doctor';}else if(result.data.type=='familyAccount'){userRole='family';}else if(result.data.type=='userAccount'){userRole='user';}onload(userRole);} }});    
}
function onload(){var currentURL = window.location.href;// console.log("当前页面路径是:" + currentURL);// console.log(userRole);var adminMatch = currentURL.match(/\/admin\//);if (adminMatch&&userRole!='admin'){alertBox("你不是管理员账户",function(){window.location.href="../home.html";});} var doctorMatch = currentURL.match(/\/doctor\//);if (doctorMatch&&userRole!='doctor'){alertBox("你不是医生账户",function(){window.location.href="../home.html";});} var familyMatch = currentURL.match(/\/family\//);if (familyMatch&&userRole!='family') {alertBox("你不是家属账户",function(){window.location.href="../home.html";});} }

后端权限控制

主要是依赖token得到用户信息
然后到拦截器进行验证

1.给所有前端请求都携带token

首先,怎么让每一个前端请求都携带token数据呢

在common.js中添加一下代码

// 设置全局AJAX参数
// 把token加入索引的请求中,后端会有权限验证
$.ajaxSetup({data: {"token": window.sessionStorage.getItem("token")}
});

这样就会使得所有前端请求都携带token数据呢

注意一点:用来在路径中直接携带token数据将会被影响

类似于一下这个

在这里插入图片描述

他会导致token变成复选框这样的请求

token=xxx,xxx

前端请求
在这里插入图片描述

后端响应:
在这里插入图片描述

如果是原先的data中请求还是有效的
只不过会覆盖原来的token
在这里插入图片描述

2.添加拦截器

package com.jsss.controller.Interceptor;import com.alibaba.fastjson.JSONObject;
import com.jsss.common.ErrorCode;
import com.jsss.common.ResponseModel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;@Component
public class LoginCheckInterceptor implements HandlerInterceptor, ErrorCode {@Autowiredprivate RedisTemplate redisTemplate;@Overridepublic boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {String token = request.getParameter("token");if (token == null || StringUtils.isBlank(token) || !redisTemplate.hasKey(token)) {response.setContentType("application/json");response.setCharacterEncoding("utf-8");PrintWriter writer = response.getWriter();Map<Object, Object> data = new HashMap<>();data.put("code", USER_NOT_LOGIN);data.put("message", "请先登录!");ResponseModel model = new ResponseModel(ResponseModel.STATUS_FAILURE, data);writer.write(JSONObject.toJSONString(model));return false;}return true;}
}

3.配置到WebMvcConfiguration

package com.jsss.configuration;import com.jsss.controller.Interceptor.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {@Autowiredprivate LoginCheckInterceptor loginCheckInterceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) {//登录拦截器配置registry.addInterceptor(loginCheckInterceptor).addPathPatterns("/**").excludePathPatterns("/user/login", "/user/register"/*,"/{path}/captcha"*/);}}

4.更多的权限验证

后端配置拦截器的一个问题【问题】

最后

2024-3-15 19:27:22

迎着日光月光星光,直面风霜雨霜雪霜。

http://www.lryc.cn/news/318854.html

相关文章:

  • 老电脑装什么系统流畅
  • 厉害了!机器视觉在农业中的应用
  • 简述从浏览器发出请求到数据返回的全过程
  • MongoDB性能最佳实践:硬件和操作系统配置
  • mysql查询条件包含IS NULL、IS NOT NULL、!=、like %* 、like %*%,不能使用索引查询,只能使用全表扫描,是真的吗???
  • 使用IDEA2023创建传统的JavaWeb项目并运行与调试
  • 【快捷部署】002_Flink(1.17.2)
  • 智慧公厕建设,助力打造宜居、韧性、可持续的智慧城市
  • [Django 0-1] Core.Cache模块
  • spy分析文件另存为弹框【selenium】
  • 分布式与集群,二者区别是什么?
  • (done) 什么是词嵌入技术?word embedding ?(这里没有介绍词嵌入算法)(没有提到嵌入矩阵如何得到)
  • C++静态成员函数和非静态成员函数之间的相互调用
  • 最好用的流程编辑器bpmn-js系列之基本使用
  • Singularity(八)| conda实战
  • elementui el-select组件多选设置初始值无法修改问题
  • 电脑自动关机后文件夹不见了怎么办?别急,找回方法在这里
  • tcp/ip协议2实现的插图,数据结构8 (30 - 32章)
  • 挑战杯 多目标跟踪算法 实时检测 - opencv 深度学习 机器视觉
  • 【数据结构】顺序表的定义及实现方式
  • R语言数据挖掘-关联规则挖掘(1)
  • 【ansible】ansible的介绍和安装
  • 二维数组_矩阵交换行
  • mysql笔记:14. 权限管理
  • 无硫防静电手指套:高科技产业的纯净与安全新选择
  • 由浅到深认识C语言(10):字符串处理函数
  • 防范服务器被攻击:查询IP地址的重要性与方法
  • 3. ElasticSearch搜索技术深入与聚合查询实战
  • 【Linux】Shell编程【一】
  • Windows10+tensorrt+python部署yolov5