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

前端权限设置【笔记】

前言

2024-3-15 18:27:26

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

版权

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

推荐

前端权限设置

需求

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

效果

访问doctor/*.html弹出"你不是医生账户",

重定向到home.html

实现

获取到当前路径currentURL

获取到当前用户角色userRole

判断这个路径是否是该角色能访问的

js 复制代码
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实现

调用栈

js 复制代码
$(document).ready(function () {
	set_login_status();{
		storage(result.data);{
			onload(userRole);
		}
	}
}

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

html 复制代码
<script src="./js/user.js"></script>
js 复制代码
$(document).ready(function () {
    // 设置用户登录状态
    set_login_status();
    // 注销按钮单击事件
    $("#btn-logout").click(function (e) { 
        logout();        
    });
});
js 复制代码
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();
            }
        }
    });    
}
js 复制代码
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) {
                //存储Account
                window.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);
             
            } 
        }
    });    
}
js 复制代码
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中添加一下代码

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

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

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

类似于一下这个

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

java 复制代码
token=xxx,xxx

前端请求

后端响应:

如果是原先的data中请求还是有效的

只不过会覆盖原来的token

2.添加拦截器

java 复制代码
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 {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public 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

java 复制代码
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 {
    @Autowired
    private LoginCheckInterceptor loginCheckInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        //登录拦截器配置
        registry.addInterceptor(loginCheckInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/user/login", "/user/register"/*,"/{path}/captcha"*/);


	}




}

4.更多的权限验证

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

最后

2024-3-15 19:27:22

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

相关推荐
学习使我快乐012 小时前
JS进阶 3——深入面向对象、原型
开发语言·前端·javascript
bobostudio19952 小时前
TypeScript 设计模式之【策略模式】
前端·javascript·设计模式·typescript·策略模式
黄尚圈圈3 小时前
Vue 中引入 ECharts 的详细步骤与示例
前端·vue.js·echarts
浮华似水4 小时前
简洁之道 - React Hook Form
前端
正小安6 小时前
如何在微信小程序中实现分包加载和预下载
前端·微信小程序·小程序
_.Switch7 小时前
Python Web 应用中的 API 网关集成与优化
开发语言·前端·后端·python·架构·log4j
一路向前的月光7 小时前
Vue2中的监听和计算属性的区别
前端·javascript·vue.js
长路 ㅤ   7 小时前
vite学习教程06、vite.config.js配置
前端·vite配置·端口设置·本地开发
长路 ㅤ   7 小时前
vue-live2d看板娘集成方案设计使用教程
前端·javascript·vue.js·live2d
Fan_web8 小时前
jQuery——事件委托
开发语言·前端·javascript·css·jquery