ss-shiro案例 (shiro登录认证授权整合,spring-boot)

241 阅读3分钟

不同的用户登录不同的页面 根据数据库权限分配

演示

image.png

cai帐号登录

image.png

image.png

image.png

lishi帐号登录

image.png

image.png

没有权限的用户登录

image.png

数据库

CREATE TABLE `user` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(32) NOT NULL DEFAULT '',
  `pwd` varchar(32) NOT NULL DEFAULT '',
  `perms` varchar(128) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8

image.png

pom.xml

//jetbrains://idea/navigate/reference?project=sprintboot&path=springboot-08-shiro/pom.xml:19:1


<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<!-- thymeleaf模板 -->
		<dependency>
			<groupId>org.thymeleaf</groupId>
			<artifactId>thymeleaf-spring5</artifactId>
		</dependency>
		<dependency>
			<groupId>org.thymeleaf.extras</groupId>
			<artifactId>thymeleaf-extras-java8time</artifactId>
		</dependency>

		<!--
		Subject	用户
		SecurityManager 管理所有用户
		Realm 连接数据
		-->
		<!-- shirog整合spring的包 -->
		<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-spring -->
		<dependency>
			<groupId>org.apache.shiro</groupId>
			<artifactId>shiro-spring</artifactId>
			<version>1.9.0</version>
		</dependency>

		<!-- shiro-thymeleaf整合 -->
		<!-- https://mvnrepository.com/artifact/com.github.theborakompanioni/thymeleaf-extras-shiro -->
		<dependency>
			<groupId>com.github.theborakompanioni</groupId>
			<artifactId>thymeleaf-extras-shiro</artifactId>
			<version>2.1.0</version>
		</dependency>


		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>

		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.2.10</version>
		</dependency>

		<!--别入myBatis,这是MyBatis官方提供的适配 Spring Boot 的,顺不是spring Boot自己的 -->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.2.2</version>
		</dependency>

		<!-- configure logging -->

		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
	</dependencies>

配置config


//jetbrains://idea/navigate/reference?project=sprintboot&path=com/cmk/springboot08shiro/config/ShiroConfig.java:20:1

@Configuration
public class ShiroConfig {

    //ShiroFilterFactoryBean:3
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();

        //设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);


        //添加shiro的内置过滤器
        /*
          anon:无需认派就可以访问
          authc:必须认证了才能让问
          user:必须佣有 记住我 功能才能用
          perms:佣有对某个资源的权限才能防间
          role:拥有某个角色权限才能访问
         */

        //拦截
        Map<String, String> filterMap = new LinkedHashMap<>();
//        fileerMap.put("/user/add","authc");
//        fileerMap.put("/user/update","authc");

        //授权,正常的情况下,没有授权会跳转到未授权页面
        filterMap.put("/user/add","perms[user:add]");
        filterMap.put("/user/update","perms[user:update]");

        filterMap.put("/user/*","authc");
        bean.setFilterChainDefinitionMap(filterMap);

        //设置登录的请求
        bean.setLoginUrl("/toLogin");

        //未授权页面
        bean.setUnauthorizedUrl("/noauth");


        return bean;
    }

    //DafaultWebSecurityManager:2
    @Bean(name="securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();

        //关联UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;

    }

    //创建 realm对象,需要自定义类:1
    @Bean(name = "userRealm")
    public UserRealm userRealm(){
        return  new UserRealm();
    }

    //整ShiroDialect:用来整合 shiro thymeleaf
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }

}

//jetbrains://idea/navigate/reference?project=sprintboot&path=com/cmk/springboot08shiro/config/UserRealm.java:21:2

//自定义的UserRealm
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权doGetAuthorizationInfo");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        info.addStringPermission("user:add");

        //拿到当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal(); //拿到user对象

        //设置当前用户的权限
        info.addStringPermission(currentUser.getPerms());
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=>doGetAuthenticationInfo");

        //用户名,密码 数据中取  (写死)
        /*
         String name = "root";
         String password = "123";

         if (!userToken.getUsername().equals(name)) {
            return null;  //抛出异常 UnknowAccountException

        */
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        //连接真实的数据库  (写活)
        User user = userService.queryUserByName(userToken.getUsername());


        if (user == null){
            return null;
        }

        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser",user);


        //密码认证,shiro做~
        return new SimpleAuthenticationInfo(user, user.getPwd(), "");
    }
}

控制器

//jetbrains://idea/navigate/reference?project=sprintboot&path=com/cmk/springboot08shiro/controller/MyController.java:17:2

@Controller
public class MyController {

    @RequestMapping({"/","/index"})
    public String toIndex(Model model){

        model.addAttribute("msg","hello,shiro");
        return "index";
    }

    @RequestMapping("/user/add")
    public String add(){
        return "user/add";
    }


    @RequestMapping("/user/update")
    public String update(){
        return "user/update";
    }

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

    @RequestMapping("/login")
    public String login(String username, String password, Model model){
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);


        try {
            subject.login(token); //执行登录方法,如果没有异常就说明ok了
            return "index";
        } catch (UnknownAccountException uae) {
            model.addAttribute("msg","用户名错误");
            return "login";
        } catch (IncorrectCredentialsException ice) {
            model.addAttribute("msg","密码错误");
            return "login";
        }catch (LockedAccountException lae) {
            model.addAttribute("msg","密码错误2");
            return "login";
        }
    }

    @RequestMapping("/noauth")
    @ResponseBody
    public String unauthorized(){
        return "未经授权无法访问此页面";
    }

}

mapper

//jetbrains://idea/navigate/reference?project=sprintboot&path=com/cmk/springboot08shiro/mapper/UserMapper.java:13:1
@Repository
@Mapper
public interface UserMapper {
    public User queryUserByName(String name);
}

pojo



//jetbrains://idea/navigate/reference?project=sprintboot&path=com/cmk/springboot08shiro/pojo/User.java:13:1
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String pwd;
    private String perms;
}

service


//jetbrains://idea/navigate/reference?project=sprintboot&path=com/cmk/springboot08shiro/service/UserService.java:11:1
public interface UserService {
    public User queryUserByName(String name);
}




//jetbrains://idea/navigate/reference?project=sprintboot&path=com/cmk/springboot08shiro/service/UserServiceImpl.java:14:1
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public User queryUserByName(String name) {
        return userMapper.queryUserByName(name);
    }
}

resources

│  application.properties
│  application.yml
│
├─mapper
│      UserMapper.xml
│
└─templates
    │  index.html
    │  login.html
    │
    └─user
            add.html
            update.html

//jetbrains://idea/navigate/reference?project=sprintboot&path=mapper/UserMapper.xml:2:1

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.cmk.springboot08shiro.mapper.UserMapper">

    <select id="queryUserByName" parameterType="string" resultType="com.cmk.springboot08shiro.pojo.User">
        select * from user where name = #{name}
    </select>


</mapper>


//templates

jetbrains://idea/navigate/reference?project=sprintboot&path=templates/index.html:3:3
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>首页</h1>
<p th:if="${session.loginUser==null}">
    <a th:href="@{/toLogin}">登录</a>
</p>
<p th:text="${msg}"></p>
<hr />
<div shiro:hasPermission="user:add">
    <a th:href="@{/user/add}">add</a>
</div>
<div shiro:hasPermission="user:update">
    <a th:href="@{/user/update}">update</a>
</div>

</body>
</html>


//jetbrains://idea/navigate/reference?project=sprintboot&path=templates/login.html:4:3
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h1>登录</h1>
<p th:text="${msg}"></p>
<form th:action="@{/login}" method="get">
    用户名:<input type="text" name="username"><br />
    密码:<input type="password" name="password"><br />
<!--    <input type="checkbox" name="remember"> 记住我<br />-->
    <input type="submit">
</form>
</body>
</html>


//jetbrains://idea/navigate/reference?project=sprintboot&path=application.properties:1:1
mybatis.type-aliases-package=com/cmk/springboot08shiro/pojo
mybatis.mapper-locations=classpath:mapper/*.xml



//jetbrains://idea/navigate/reference?project=sprintboot&fqn=spring
spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    #sping boot默认是不注入这些属性值的,需求自己绑定
    #druid 数据源专用配置
    initialsize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500