Springboot简单授权,限制访问

导读:本篇文章讲解 Springboot简单授权,限制访问,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

提示:以下是部分代码,全部代码链接

链接:https://pan.baidu.com/s/14wTJ53RR1zDIiX4YXt4XDw 
提取码:thk6

思路:

1.获取请求头中token,从redis中获取当前登录对象的id    方法:   request.getHeader(“token”)

2.通过用户id到数据库中查询当前登录对象的角色,获取到角色id

3.通过角色id关联查询当前登录对象能访问的url    返回ArrayList<power>

4.请求头中获取当前访问接口的url路径                              方法:request.getRequestURI();

5.将ArrayList遍历,获取ArrayList中的url 放入一个新的ArrayList<String>中

6.遍历ArrayList<String>,判断里面是否包含从请求头中获取的方法(如果有说明当前登陆对象有权限访问该资源,如果没有说明当前登录对象没有权限访问,返回401,msg=”您没有权限访问,请充钱……,只有充钱才能让你变得更加强大!”)

数据库设计

用户表:

CREATE TABLE `people` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT ‘id’,
  `name` varchar(20) DEFAULT NULL COMMENT ‘姓名’,
  `sex` char(1) DEFAULT NULL COMMENT ‘性别(0女,1男)’,
  `age` int(20) DEFAULT NULL COMMENT ‘年龄’,
  `address` varchar(20) DEFAULT NULL COMMENT ‘地址’,
  `user_name` varchar(20) DEFAULT NULL COMMENT ‘用户名’,
  `pwd` varchar(50) DEFAULT NULL COMMENT ‘密码’,
  `email` varchar(20) DEFAULT NULL COMMENT ‘邮箱’,
  `phonenumber` varchar(20) DEFAULT NULL COMMENT ‘电话’,
  `login_ip` varchar(20) DEFAULT NULL COMMENT ‘最后登录IP’,
  `status` char(1) DEFAULT NULL COMMENT ‘帐号状态(0正常 1停用)’,
  `login_date` datetime DEFAULT NULL COMMENT ‘最后登录时间’,
  `create_by` varchar(20) DEFAULT NULL COMMENT ‘创建者’,
  `create_time` datetime DEFAULT NULL COMMENT ‘创建时间’,
  `update_by` varchar(20) DEFAULT NULL COMMENT ‘修改者’,
  `update_time` datetime DEFAULT NULL COMMENT ‘修改时间’,
  `remark` varchar(255) DEFAULT NULL COMMENT ‘备注’,
  `roleid` bigint(20) DEFAULT NULL COMMENT ‘角色id’,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6918579172826951681 DEFAULT CHARSET=utf8;

角色表:

CREATE TABLE `role` (
  `id` bigint(20) NOT NULL COMMENT ‘id’,
  `rolename` varchar(25) DEFAULT NULL COMMENT ‘角色名称’,
  `powerid` bigint(20) DEFAULT NULL COMMENT ‘权限id’,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

权限表:

CREATE TABLE `power` (
  `id` bigint(20) NOT NULL COMMENT ‘id’,
  `url` varchar(255) DEFAULT NULL COMMENT ‘地址’,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

角色权限中间表:

CREATE TABLE `rolemiddle` (
  `id` bigint(20) NOT NULL COMMENT ‘id’,
  `roleid` bigint(20) DEFAULT NULL COMMENT ‘角色id’,
  `powerid` bigint(20) DEFAULT NULL COMMENT ‘权限id’,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

关联关系:

用户表中的roleid(角色id) 与角色表  一对一

用户表与权限表   一对多

实体类:

用户表

package com.thk.domain;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.Date;

public class People extends BaseEntity {
    /**
     * id
     */
    private Long id;
    /**
     * 姓名
     */
    @Size(min = 0, max = 30, message = "用户昵称长度不能超过30个字符")
    private String name;
    /**
     * 年龄
     */
    private Integer age;
    /**
     * 性别
     */
    private String sex;

    /**
     * 地址
     */
    private String address;
    /**
     * 用户名
     */
    @NotBlank(message = "用户账号不能为空")
    @Size(min = 0, max = 30, message = "用户账号长度不能超过30个字符")
    private String userName;
    /**
     * 密码
     */
    private String pwd;
    /**
     * 邮箱
     */
    @Email(message = "邮箱格式不正确")
    @Size(min = 0, max = 50, message = "邮箱长度不能超过50个字符")
    private String email;
    /**
     * 电话
     */
    @Size(min = 0, max = 11, message = "手机号码长度不能超过11个字符")
    private String phonenumber;
    /**
     * 最后登录IP
     */
    private String loginIp;
    /**
     * 帐号状态(0正常 1停用)
     */
    private String status;
    /**
     * 最后登录时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date loginDate;

    /**
     * 角色id
     */
    private Long roleid;

    public Long getRoleid() {
        return roleid;
    }

    public void setRoleid(Long roleid) {
        this.roleid = roleid;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }


    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Size(min = 0, max = 30, message = "用户昵称长度不能超过30个字符")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @NotBlank(message = "用户账号不能为空")
    @Size(min = 0, max = 10, message = "用户账号长度不能超过10个字符")
    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    @JsonIgnore
    @JsonProperty
    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    @Email(message = "邮箱格式不正确")
    @Size(min = 0, max = 50, message = "邮箱长度不能超过50个字符")
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Size(min = 0, max = 11, message = "手机号码长度不能超过11个字符")
    public String getPhonenumber() {
        return phonenumber;
    }

    public void setPhonenumber(String phonenumber) {
        this.phonenumber = phonenumber;
    }

    public String getLoginIp() {
        return loginIp;
    }

    public void setLoginIp(String loginIp) {
        this.loginIp = loginIp;
    }

    public Date getLoginDate() {
        return loginDate;
    }

    public void setLoginDate(Date loginDate) {
        this.loginDate = loginDate;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public People() {
    }

    @Override
    public String toString() {
        return "People{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                ", userName='" + userName + '\'' +
                ", pwd='" + pwd + '\'' +
                ", email='" + email + '\'' +
                ", phonenumber='" + phonenumber + '\'' +
                ", loginIp='" + loginIp + '\'' +
                ", status='" + status + '\'' +
                ", loginDate=" + loginDate +
                ", roleid=" + roleid +
                '}';
    }
}

角色表

package com.thk.domain;


import lombok.Data;

/**
 * 角色对象 role
 * 
 * @author thk
 * @date 2022-04-29
 */
@Data
public class Role extends BaseEntity
{

    /** id */
    private Long id;

    /** 角色名称 */
    private String rolename;

    /** 权限id */
    private Long powerid;

}

权限表

package com.thk.domain;

import lombok.Data;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

/**
 * 权限表对象 power
 * 
 * @author thk
 * @date 2022-04-29
 */
@Data
public class Power extends BaseEntity
{

    /** id */
    private Long id;

    /** 地址 */
    private String url;

}

controller

/**
 * 查询全部用户 分页
 *
 * @param people
 * @return
 */
@GetMapping("/selectAll")
public TableDataInfo selectAll(People people, HttpServletRequest request, HttpServletResponse response) {
    if (verifyPermissions(request)) {
        return errorDataTable();
    }
    //判断是否有权限
    if (!competence(request)) {
        return errorDataTable();
    }
    startPage();
    List<People> list = peopleService.selectAll(people);
    return getDataTable(list);
}

/**
 * 查询全部用户 不分页
 *
 * @param people
 * @param request
 * @param response
 * @return
 */
@GetMapping("/list")
public AjaxResult list(People people, HttpServletRequest request, HttpServletResponse response) {
    if (verifyPermissions(request)) {
        return AjaxResult.error(HttpStatus.UNAUTHORIZED, "非法访问,请先登录");
    }
    //判断是否有权限
    if (!competence(request)) {
        return AjaxResult.error(HttpStatus.UNAUTHORIZED, "您没有权限访问,只有充钱才能让你变得更加强大,请充钱......");
    }
    List<People> list = peopleService.selectAll(people);
    return AjaxResult.success(list);
/**
 * 判断是否有权限
 *
 * @param request
 * @return
 */
public boolean competence(HttpServletRequest request) {
    //request.getHeader("token")------从请求头中获取token
    //getUserId(request.getHeader("token"))----获取当前登录对象的id
    //获取当前登录对象的全部信息
    People people = peopleMapper.selectById(getUserId(request.getHeader("token")));
    //从请求头中获取的地址
    String requestURI = request.getRequestURI();
    //通过角色id查询当前登陆对象的所有权限
    List<Power> list = powerMapper.selectUrl(people.getRoleid());
    ArrayList<String> list1 = new ArrayList<>();
    if (!StringUtils.isEmpty(list)) {
        list.forEach(r -> {
            list1.add(r.getUrl());
        });
        return lsitUtils.ifcontain(list1, requestURI);
    }
    return false;
}
/**
 * 获取登录用户id
 */
public Long getUserId(String token) {
    Object o = redisUtil.get(token);
    if (!StringUtils.isNull(o)) {
        Long id = Long.valueOf(String.valueOf(o));
        return id;
    }
    throw new NullPointerException();
}
/**
 * 判断集合中是否存在某个字符串  限制String类型的list
 * @param list
 * @param str
 * @return
 */
public  boolean ifcontain(Collection<?> list, String str){
    boolean b =false;
    for (Object o : list) {
        if (o.equals(str)) {
            return b = true;
        }
    }
    return b;
}
}

service

/**
 * 查询全部用户
 *
 * @param people
 * @return
 */
List<People> selectAll(People people);

service实现类:

/**
 * 查询全部用户
 *
 * @param people
 * @return
 */
@Override
public List<People> selectAll(People people) {
    List<People> list = baseMapper.selectLists(people);
    list.forEach(r -> {
        if (r.getSex() == null) {
            r.setSex(Constant.UNKNOWN);
        }
        if (Constant.MALE.equals(r.getSex())) {
            r.setSex(Constant.MAN);
        }

        if (Constant.GIRL.equals(r.getSex())) {
            r.setSex(Constant.WOMAN);
        }
    });
    return list;
}

mapper

/**
 * 查询全部用户
 * @param people
 * @return
 */
List<People> selectLists(People people);

mapper.xml

<!--查询url-->
<select id="selectUrl" resultType="com.thk.domain.Power">
        SELECT p.url FROM rolemiddle as  r
        LEFT JOIN power as p  ON r.powerid=p.id
        WHERE r.roleid=#{id}
</select>

<!--查询全部用户-->
<select id="selectLists" resultType="com.thk.domain.People">
    <include refid="selectPeopleVo"/>
    <where>
        <if test="name != null  and name != ''">and name like concat('%', #{name}, '%')</if>
        <if test="age != null ">and age = #{age}</if>
        <if test="sex != null ">and sex = #{sex}</if>
        <if test="address != null  and address != ''">and address = #{address}</if>
        <if test="userName != null  and userName != ''">and user_name like concat('%', #{userName}, '%')</if>
        <if test="pwd != null  and pwd != ''">and pwd = #{pwd}</if>
        <if test="email != null  and email != ''">and email = #{email}</if>
        <if test="phonenumber != null  and phonenumber != ''">and phonenumber = #{phonenumber}</if>
        <if test="loginIp != null  and loginIp != ''">and login_ip = #{loginIp}</if>
        <if test="status != null  and status != ''">and status = #{status}</if>
        <if test="loginDate != null ">and login_date = #{loginDate}</if>
    </where>
</select>

测试

admin拥有全部权限

总经理拥有全部权限

员工只能查询

Springboot简单授权,限制访问

Springboot简单授权,限制访问

admin测试:

登录获取token

Springboot简单授权,限制访问

 admin查询全部

Springboot简单授权,限制访问

 员工测试:

员工登录获取token

Springboot简单授权,限制访问

 员工查询全部

Springboot简单授权,限制访问

删除员工的查询权限:

删除前

Springboot简单授权,限制访问

删除后

Springboot简单授权,限制访问

 员工查询全部

Springboot简单授权,限制访问

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/119874.html

(0)
seven_的头像seven_bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!