• 记录个人的权限管理逻辑


    本人使用的是spring boot 

    写一个工具类如下:

    package com.test.package;
    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    import org.springframework.stereotype.Component;
    
    @Component
    public class SpringContextUtil implements ApplicationContextAware {
        private static ApplicationContext applicationContext;
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            SpringContextUtil.applicationContext = applicationContext;
        }
        public static ApplicationContext getApplicationContext() {
            return applicationContext;
        }
    
        //通过名字获取上下文中的bean
        public static Object getBean(String name){
            return applicationContext.getBean(name);
        }
    
        //通过类型获取上下文中的bean
        public static Object getBean(Class<?> requiredType){
            return applicationContext.getBean(requiredType);
        }
    }
    

      

    在你要使用的地方直接使用即可:(我要使用

    JedisServer 这个server 类

    ),此处作为权限认证部分

    package com.huis.portal.filter;
    
    import com.alibaba.fastjson.JSON;
    import com.huis.common.util.JsonResultEntity;
    import com.huis.portal.SpringContextUtil;
    import com.huis.portal.service.JedisServer;
    import org.springframework.util.AntPathMatcher;
    import org.springframework.util.PathMatcher;
    import org.springframework.web.filter.OncePerRequestFilter;
    
    import javax.servlet.FilterChain;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.util.Date;
    import java.util.List;
    import java.util.Map;
    
    
    public class JwtAuthenticationFilter extends OncePerRequestFilter {
    
        private JedisServer jedisServer = (JedisServer) SpringContextUtil.getBean("jedisServerImpl");
    
        private static final PathMatcher PATH_MATCHER = new AntPathMatcher();
    
        public JwtAuthenticationFilter() {
        }
    
        @Override
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
                throws ServletException, IOException {
            JsonResultEntity JsonResultEntity = new JsonResultEntity();
            JsonResultEntity.setCode(201);
            JsonResultEntity.setMessage("token有误");
            String uid = "";
            try {
                if (isSellerProtectedUrl(request)) {
                    Map<String, Object> claims = JwtUtil.validateTokenAndGetClaims(request, response);
                    String url = request.getServletPath();
                    uid = (String) claims.get("uid");
                    String time = claims.get("exp") + "000";
                    Date date1 = new Date(Long.parseLong(time));
                    if (new Date().after(date1)) {
                        response.setCharacterEncoding("UTF-8");
                        response.getWriter().print(JSON.toJSONString(JsonResultEntity));
                        return;
                    }
                    String resource = (String) claims.get("RESOURCE" + uid);
                    List<String> list = (List<String>) JSON.parse(resource);
                    JsonResultEntity.setCode(202);
                    JsonResultEntity.setMessage("您无此操作权限");
                    if (list != null && list.size() > 1) {
                        if (!list.contains(url)) {
                            response.setCharacterEncoding("UTF-8");
                            response.getWriter().print(JSON.toJSONString(JsonResultEntity));
                            return;
                        }
                    } else {
                        response.setCharacterEncoding("UTF-8");
                        response.getWriter().print(JSON.toJSONString(JsonResultEntity));
                        return;
                    }
                }
            } catch (Exception e) {
                response.setCharacterEncoding("UTF-8");
                response.getWriter().print(JSON.toJSONString(JsonResultEntity));
                return;
            }
            request.setAttribute("uid", uid);
            filterChain.doFilter(request, response);
        }
    
        private boolean isSellerProtectedUrl(HttpServletRequest request) {
         //从redis获取所有权限进行匹配
            String allResource = jedisServer.get("REDIS_KEY_FOR_ALL_RESOURCE");
            List<String> list = (List<String>) JSON.parse(allResource);
            for (String str : list) {
                if (PATH_MATCHER.match(str, request.getServletPath())) {
                    return true;
                }
            }
            return false;
        }

     要用到的统一返回工具类

    package com.huis.common.util;
    
    public class JsonResultEntity {
    
        private Object data;
        private String message;
        private Integer code;
    
        public Object getData() {
            return data;
        }
    
        public void setData(Object data) {
            this.data = data;
        }
    
        public String getMessage() {
            return message;
        }
    
        public void setMessage(String message) {
            this.message = message;
        }
    
        public Integer getCode() {
            return code;
        }
    
        public void setCode(Integer code) {
            this.code = code;
        }
    }
    JWT类
    package com.huis.portal.filter;
    
    import com.alibaba.fastjson.JSON;
    import com.huis.common.util.JsonResultEntity;
    import io.jsonwebtoken.Jwts;
    import io.jsonwebtoken.SignatureAlgorithm;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.Map;
    
    public class JwtUtil {
        public static final long EXPIRATION_TIME = 1000 * 60 * 60 * 24 * 10;
        public static final String SECRET = "P@hu12ceshi";
        public static final String TOKEN_PREFIX = "ceshi";
        public static final String HEADER_STRING = "ceshi";
        public static final String ROLE = "ceshi";
    
        // 为后台生成token并将权限放入token内(resource为JSON格式)
        public static String generateTokenForSeller(String uid, Date gentTime, String resource) {
            HashMap<String, Object> map = new HashMap<>();
            // 可以把任何安全的数据放到map里面
            map.put(ROLE, uid);
            map.put("RESOURCE"+uid, resource);
            map.put("uid", uid);
            map.put("gentTime", gentTime);
            String jwt = Jwts.builder()
                    .setClaims(map)
                    .setExpiration(new Date(gentTime.getTime() + EXPIRATION_TIME))
                    .signWith(SignatureAlgorithm.HS512, SECRET)
                    .compact();
            return TOKEN_PREFIX + jwt;
        }
    
        // 验证token
        public static Map<String, Object> validateTokenAndGetClaims(HttpServletRequest request, HttpServletResponse response) throws IOException {
            String token = request.getHeader(HEADER_STRING);
            if (token == null) {
                JsonResultEntity JsonResultEntity = new JsonResultEntity();
                JsonResultEntity.setCode(201);
                JsonResultEntity.setMessage("token有误");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().print(JSON.toJSONString(JsonResultEntity));
                return null;
            }
            Map<String, Object> body = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                    .getBody();
            return body;
        }
    }

    要用到的VO类

    package com.huis.dao.vo;
    
    
    import java.io.Serializable;
    
    public class UserVo implements Serializable{
        private Integer uid;
        private String email;
        private String mobile;
        private String username;
        private String token;
        private String openId;
        private String sessionKey;
        private Integer staus;
        private String shopId;
     //get和set 方法 
    }

    登陆的时候将个人拥有的权限放到token里面,将需要管理的权限放到redis里面

    SellerUsersEntity checkUser = sellerUsersService.checkUser(username);
    sellerUsersService.updateLastLogin(checkUser.getUid());
    checkUser = sellerUsersService.checkUser(username);
    List<String> list = resourcesService.findUserPermissions(checkUser.getUid());
    if(list.size() == 0 || list==null) {
    list.add("您没有权限");
    }
    String jwt = JwtUtil.generateTokenForSeller(String.valueOf(checkUser.getUid()), new Date(),JSON.toJSONString(list));
    UserVo userVo = new UserVo();
    userVo.setUid(checkUser.getUid());
    userVo.setToken(jwt);
    userVo.setUsername(username);
    List<String> resourceList = resourcesMapper.queryAllResource();
    jedisServer.set(UsersStatusEnum.REDIS_KEY_FOR_ALL_RESOURCE.getMessage(),JSON.toJSONString(resourceList));

    权限下面5张表。增删改查操作自行解决

    用户表,

    package com.huis.dao.entity;
    
    import java.util.Date;
    
    /**
     * @author luowangcheng
     */
    public class SellerUsersEntity {
        private Integer uid;
        private String username;
        private String password;
        private String salt;
        private String mobile;
        private Integer status;
        private Date regTime;
        private Date lastTime;    
       //get和set 方法 
    }



    CREATE TABLE `seller_users` (
    `uid` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '用户ID',
    `username` varchar(64) NOT NULL DEFAULT '' COMMENT '用户名',
    `password` varchar(32) NOT NULL DEFAULT '' COMMENT '密码',
    `salt` varchar(6) NOT NULL DEFAULT '' COMMENT '密码加盐',
    `mobile` varchar(16) DEFAULT '' COMMENT '手机号',
    `status` tinyint(4) unsigned DEFAULT '0' COMMENT '账号状态',
    `reg_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `last_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最后一次登录时间',
    PRIMARY KEY (`uid`)
    ) ENGINE=InnoDB AUTO_INCREMENT=69 DEFAULT CHARSET=utf8 COMMENT='后台用户信息表';

    用户角色表。

    package com.huis.dao.entity;
    
    import java.io.Serializable;
    
    public class UserRole implements Serializable{        
        private Integer uid;
        private Integer roleId;
        //get和set 方法 
    }

    CREATE TABLE `user_role` (
    `uid` int(11) DEFAULT NULL,
    `role_id` int(11) DEFAULT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

    角色表,

    package com.huis.dao.entity;
    
    import java.io.Serializable;
    
    public class Role implements Serializable{  
        //角色id
        private Integer id;
        //角色名
        private String roleDesc;
        //所属部门id
        private Integer departmentId;
        //所属部门名
        private String departmentName;
            //get和set 方法 
    }

    CREATE TABLE `role` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `role_desc` varchar(255) DEFAULT NULL,
    `department_id` int(11) DEFAULT NULL,
    `department_name` varchar(255) DEFAULT '',
    PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8;

    角色权限表。

    package com.huis.dao.entity;
    
    import java.io.Serializable;
    
    public class RoleResources implements Serializable{
        private Integer roleId;
        private Integer resourcesId;
            //get和set 方法 
    }

    CREATE TABLE `role_resources` (
    `role_id` int(11) NOT NULL,
    `resources_id` int(11) NOT NULL,
    PRIMARY KEY (`role_id`,`resources_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

    权限表

    package com.huis.dao.entity;
    
    import java.io.Serializable;
    
    public class Resources implements Serializable{
        private Integer id;
        /**
         * 资源名称
         */
        private String name;
        /**
         * 资源url
         */
        private String resourceUrl;
        /**
         * 资源类型   1:菜单    2:按钮
         */
        private Integer type;
        /**
         * 父资源
         */
        private Integer parentId;
        /**
         * 排序
         */
        private Integer sort;
            //get和set 方法 
    }

    CREATE TABLE `resources` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `name` varchar(255) DEFAULT NULL COMMENT '资源名称',
    `resource_url` varchar(255) DEFAULT NULL COMMENT '资源url',
    `type` int(11) DEFAULT NULL COMMENT '资源类型 1:菜单 2:按钮',
    `parent_id` int(11) DEFAULT NULL COMMENT '父资源',
    `sort` int(11) DEFAULT NULL COMMENT '排序',
    PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=84 DEFAULT CHARSET=utf8;

  • 相关阅读:
    HTML5 ④
    HTML5 ③
    HTML5 ②
    HTML5 ①
    what’s this?
    第一篇
    2017年3月1号课堂笔记
    2017年2月27号课堂笔记
    2017年2月24号课堂笔记
    2017.02.15课堂笔记
  • 原文地址:https://www.cnblogs.com/hahahehexixihoho/p/9729327.html
Copyright © 2020-2023  润新知