栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot-shiro权限控制

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot-shiro权限控制

1、建立权限相关表

##用户表
CREATE TABLE `t_user` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `USERNAME` varchar(128) NOT NULL COMMENT '用户名',
  `PASSWD` varchar(128) NOT NULL COMMENT '密码',
  `CREATE_TIME` datetime DEFAULT NULL COMMENT '创建时间',
  `STATUS` char(1) NOT NULL COMMENT '是否有效 1:有效  0:锁定STATUS',
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

INSERT INTO t_user VALUES ('1','admin', '1fedc5a36d03c185065dd2b323886aa5', '2022-06-01 17:20:21', '0');
INSERT INTO t_user VALUES ('2','test', '7a38c13ec5e9310aed731de58bbc4214','2022-06-01 10:52:48', '1');

##角色表
CREATE TABLE `t_role` (
  `ID` int(11) NOT NULL,
  `NAME` varchar(255) DEFAULT NULL COMMENT '角色名称',
  `MEMO` varchar(255) DEFAULT NULL COMMENT '角色描述'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO t_role VALUES ('1', 'admin', '超级管理员');
INSERT INTO t_role VALUES ('2', 'test', '测试账户');


##功能权限表
CREATE TABLE `t_permission` (
  `ID` int(10) NOT NULL,
  `URL` varchar(255) DEFAULT NULL COMMENT 'url地址',
  `NAME` varchar(64) DEFAULT NULL COMMENT 'url描述'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO t_permission VALUES ('1', '/user', 'user:user');
INSERT INTO t_permission VALUES ('2', '/user/add', 'user:add');
INSERT INTO t_permission VALUES ('3', '/user/delete', 'user:delete');

##用户-角色表
CREATE TABLE `t_user_role` (
  `USER_ID` int(10) DEFAULT NULL COMMENT '用户id',
  `RID` int(10) DEFAULT NULL COMMENT '角色id'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO t_user_role VALUES ('1', '1');
INSERT INTO t_user_role VALUES ('2', '2');


##角色-权限表
CREATE TABLE `t_role_permission` (
  `RID` int(10) NOT NULL COMMENT '角色id',
  `PID` int(10) DEFAULT NULL COMMENT '权限id'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO t_role_permission VALUES ('1', '2');
INSERT INTO t_role_permission VALUES ('1', '3');
INSERT INTO t_role_permission VALUES ('2', '1');
INSERT INTO t_role_permission VALUES ('1', '1');

2、引入shiro依赖



    org.apache.shiro
    shiro-spring
    1.4.1

3、创建并生成pojo、dao、mapper映射、service、service实现类

3.1、pojo实体

        3.1.1、User实体

package com.***.***.pojo;
 
import java.util.Date;
 
public class User {
    private Integer id;
    private String username;
    private String passwd;
    private Date createTime;
    private String status;
 
    public Integer getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPasswd() {
        return passwd;
    }

    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public String getStatus() {
        return status;
    }

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

        3.1.2、Permission实体类

package com.***.***.pojo;

import java.io.Serializable;

public class Permission implements Serializable {
    private Integer id;

    private String url;

    private String name;

    public Integer getId() {
        return id;
    }

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

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getName() {
        return name;
    }

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

        3.1.3、Role实体类

package com.***.***.pojo;

import java.io.Serializable;

public class Role implements Serializable {
    private Integer id;

    private String name;

    private String memo;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getMemo() {
        return memo;
    }

    public void setMemo(String memo) {
        this.memo = memo;
    }
}

3.2、dao方法

        3.2.1、UserMapper

package com.***.***.dao;

import com.***.***.pojo.User;

public interface UserMapper {
    User findByUserName(String userName);
}

        3.2.2、PermissionMapper

package com.***.***.dao;

import com.***.***.pojo.Permission;

import java.util.List;

public interface PermissionMapper {

    List findByUserName(String userName);
}

        3.2.3、RoleMapper

package com.***.***.dao;

import com.***.***.pojo.Role;

import java.util.List;

public interface RoleMapper {

    List findByUserName(String userName);
}

3.3、service业务逻辑层

        3.3.1、UserService

package com.***.***.service;

import com.***.***.pojo.User;

public interface UserService {

    User findByUserName(String userName);
}

        3.3.2、PermissionService

package com.***.***.service;

import com.***.***.pojo.Permission;

import java.util.List;

public interface PermissionService {

    List findByUserName(String userName);
}

        3.3.3、RoleService

package com.***.***.service;

import com.***.***.pojo.Role;

import java.util.List;

public interface RoleService {

    List findByUserName(String userName);
}

3.4、impl业务逻辑实现层

        3.4.1、UserServiceImpl

package com.***.***.service.impl;

import com.***.***.pojo.User;
import com.***.***.dao.UserMapper;
import com.***.***.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    public User findByUserName(String userName) {
        return this.userMapper.findByUserName(userName);
    }
}

        3.4.2、PermissionServiceImpl

package com.***.***.service.impl;

import com.***.***.dao.PermissionMapper;
import com.***.***.pojo.Permission;
import com.***.***.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    public List findByUserName(String userName){
        return permissionMapper.findByUserName(userName);
    }


}

        3.4.3、RoleServiceImpl

package com.***.***.service.impl;

import com.***.***.dao.RoleMapper;
import com.***.***.pojo.Role;
import com.***.***.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    public List findByUserName(String userName){
        return roleMapper.findByUserName(userName);
    }
}

3.5、mapper映射

        3.5.1、UserMapper.xml




    
        
        
        
        
        
    

    
	select p.id,p.url,p.name from t_role r
	left join t_user_role ur on(r.id = ur.rid)
	left join t_user u on(u.id = ur.user_id)
	left join t_role_permission rp on(rp.rid = r.id)
	left join t_permission p on(p.id = rp.pid )
	where u.username = #{userName}


        3.5.3、RoleMapper.xml




  
    
    
    
  

  

4、shiro配置及工具类

        4.1、shiro用户认证和权限认证

package com.***.***.shiro;

import com.***.***.dao.PermissionMapper;
import com.***.***.dao.RoleMapper;
import com.***.***.pojo.Permission;
import com.***.***.pojo.Role;
import com.***.***.pojo.User;

import com.***.***.service.PermissionService;
import com.***.***.service.RoleService;
import com.***.***.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;


public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private RoleService roleService;

    
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {

        User user = (User) SecurityUtils.getSubject().getPrincipal();
        String userName = user.getUsername();

        System.out.println("用户" + userName + "获取权限-----ShiroRealm.doGetAuthorizationInfo");
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        // 获取用户角色集
        List roleList = roleService.findByUserName(userName);
        Set roleSet = new HashSet<>();
        for (Role r : roleList) {
            roleSet.add(r.getName());
        }
        simpleAuthorizationInfo.setRoles(roleSet);

        // 获取用户权限集
        List permissionList = permissionService.findByUserName(userName);
        Set permissionSet = new HashSet();
        for (Permission p : permissionList) {
            permissionSet.add(p.getName());
        }
        simpleAuthorizationInfo.setStringPermissions(permissionSet);
        return simpleAuthorizationInfo;
    }

    
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());
        System.out.println("用户" + userName + "认证-----ShiroRealm.doGetAuthenticationInfo");

        //数据库匹配用户
        User user = userService.findByUserName(userName);
        if (user == null) {
            throw new UnknownAccountException("用户名或密码错误!");
        }
        if (!password.equals(user.getPasswd())) {
            throw new IncorrectCredentialsException("用户名或密码错误!");
        }
        if (user.getStatus().equals("0")) {
            throw new LockedAccountException("账号已被锁定,请联系管理员!");
        }
        //匹配成功,返回用户信息
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
        return info;
    }
}

        4.2、shiro拦截器

package com.***.***.config;

import java.util.LinkedHashMap;

import com.***.***.shiro.ShiroRealm;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ShiroConfig {

    @Bean("shiroFilter")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        shiroFilterFactoryBean.setLoginUrl("/login");
        shiroFilterFactoryBean.setSuccessUrl("/index");
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");

        LinkedHashMap filterChainDefinitionMap = new LinkedHashMap<>();

        filterChainDefinitionMap.put("/css
    public SimpleCookie rememberMeCookie() {
        // 设置cookie名称,对应login.html页面的
        SimpleCookie cookie = new SimpleCookie("rememberMe");
        // 设置cookie的过期时间,单位为秒,这里为一天
        cookie.setMaxAge(86400);
        return cookie;
    }

    
    public CookieRememberMeManager rememberMeManager() {
        CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
        cookieRememberMeManager.setCookie(rememberMeCookie());
        // rememberMe cookie加密的密钥
        cookieRememberMeManager.setCipherKey(Base64.decode("3AvVhmFLUs0KTA3Kprsdag=="));
        return cookieRememberMeManager;
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
}

        4.3、MD5加密工具类

package com.***.***.util;


import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

public class MD5Utils {

    private static final String SALT = "mrbird";

    private static final String ALGORITH_NAME = "md5";

    private static final int HASH_ITERATIONS = 2;

    public static String encrypt(String pswd) {
        String newPassword = new SimpleHash(ALGORITH_NAME, pswd, ByteSource.Util.bytes(SALT), HASH_ITERATIONS).toHex();
        return newPassword;
    }

    public static String encrypt(String username, String pswd) {
        String newPassword = new SimpleHash(ALGORITH_NAME, pswd, ByteSource.Util.bytes(username + SALT),
                HASH_ITERATIONS).toHex();
        return newPassword;
    }
}

5、控制器

        5.1、LoginController

package com.***.***.controller;

import com.***.***.pojo.ResponseBo;
import com.***.***.pojo.User;
import com.***.***.util.MD5Utils;
import org.springframework.stereotype.Controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class LoginController {

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public ResponseBo login(String username, String password,Boolean rememberMe) {
        //将用户名密码加密
        password = MD5Utils.encrypt(username, password);
        //shiro令牌
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            return ResponseBo.ok();
        } catch (UnknownAccountException e) {
            return ResponseBo.error(e.getMessage());
        } catch (IncorrectCredentialsException e) {
            return ResponseBo.error(e.getMessage());
        } catch (LockedAccountException e) {
            return ResponseBo.error(e.getMessage());
        } catch (AuthenticationException e) {
            return ResponseBo.error("认证失败!");
        }
    }

    @RequestMapping("/")
    public String redirectIndex() {
        return "redirect:/index";
    }

    @RequestMapping("/index")
    public String index(Model model) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        model.addAttribute("user", user);
        return "index";
    }

    @GetMapping("/403")
    public String forbid() {
        return "403";
    }
}

        5.2、UserController

package com.***.***.controller;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Controller
@RequestMapping("/user")
public class UserController {

    @RequiresPermissions("user:user")
    @RequestMapping("/list")
    public String userList(Model model) {
        model.addAttribute("value", "获取信息");
        return "user";
    }

    @RequiresPermissions("user:add")
    @RequestMapping("/add")
    public String userAdd(Model model) {
        model.addAttribute("value", "新增");
        return "user";
    }

    @RequiresPermissions("user:delete")
    @RequestMapping("/delete")
    public String userDelete(Model model) {
        model.addAttribute("value", "删除");
        return "user";
    }
}

        5.3、自定义统一异常处理

package com.***.***.config;

import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DiyExceptionHandler implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        if (e instanceof UnauthorizedException) { // 未授权 : 403
            ModelAndView mv = new ModelAndView("/403");
            return mv;
        } else if (e instanceof UnauthenticatedException) { // 未认证 : 401
            ModelAndView mv = new ModelAndView("/login");
            return mv;
        }
        return null;
    }
}

        5.4、注册统一异常处理bean

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import com.***.***.config.DiyExceptionHandler;

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
    
    // 注册统一异常处理bean
    @Bean
    public DiyExceptionHandler diyExceptionHandler() {
        return new DiyExceptionHandler ();
    }
}

6、测试页面

        6.1、登录页面login.html




    
    登录
    
    



    
        
        
        

记住我

 

 

        6.2、登录成功页面index.html




    
    首页



你好![[${user.username}]]

权限测试链接 获取用户信息 新增用户 删除用户 注销

 

 

        6.3、功能权限测试页user.html




    
    [[${value}]]


[[${value}]]

返回

 

 

        6.4、无权限跳转页面403.html




    
    暂无权限


您没有权限访问该资源!!

返回

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/946743.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号