这个小项目包含了注册与登录,使用了springboot+mybatis+shiro的技术栈;当用户在浏览器登录时发起请求时,首先这一系列的请求会被拦截器进行拦截(ShiroFilter),然后拦截器根据用户名去数据库寻找是否有相对应的user实体;如果有则返回封装到User类中(没有就用户名错误),然后比对密码是否一致;如果都通过了则认证成功;登录到主页面;然后主页面有不同的功能,不同的用户拥有不同的权限,有的能看到,有的则无法看到;然后如果不登陆直接访问主页面,会被强制跳转到登录页面;另外登录之后也可以退出登录;

通过分析上文:https://blog.csdn.net/Kevinnsm/article/details/11187650

1.首先快速创建一个springboot项目(使用spring向导)

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.hao</groupId>
    <artifactId>springboot-shiro</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-shiro</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>
    <!--########################################################-->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring-boot-starter</artifactId>
            <version>1.7.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.19</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
    </dependencies>
    <!--########################################################-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

2.数据库建表
在这里插入图片描述

这里的salt字段主要是为了使用md5+salt+散列加密时,需要保存salt字符串,以便在业务层比较密码正确与否时一致

3.注册、登录和主页面

<%@page contentType="text/html; utf-8" pageEncoding="UTF-8" isELIgnored="false" %>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>用户注册</h1>
    <form action="${pageContext.request.contextPath}/user/register" method="post">
        username:<input type="text" name="username"><br>
        password:<input type="password" name="password"><br>
        <input type="submit" value="注册">
    </form>
</body>
</html>
<%@page contentType="text/html; utf-8" pageEncoding="UTF-8" isELIgnored="false" %>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>用户登录</h1>
    <form action="${pageContext.request.contextPath}/user/login" method="post">
        username:<input type="text" name="username"><br>
        password:<input type="password" name="password"><br>
        <input type="submit" value="登录">
    </form>
</body>
</html>
<%@page contentType="text/html; utf-8" pageEncoding="UTF-8" isELIgnored="false" %>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>系统主页,欢迎你的到来</h1>
    <a href="${pageContext.request.contextPath}/user/outLogin">退出</a>

    <ul>
        <shiro:hasAnyRoles name="user">
            <li><a href="">用户管理</a>
                <ul>
                    <shiro:hasPermission name="user:add:*">
                        <li><a href="">添加用户</a></li>
                    </shiro:hasPermission>
                    <li><a href="">删除用户</a></li>
                    <li><a href="">修改用户</a></li>
                    <li><a href="">查询用户</a></li>
                </ul>
            </li>
        </shiro:hasAnyRoles>
        <shiro:hasRole name="admin">
            <li><a href="">商品管理</a> </li>
            <li><a href="">订单管理</a> </li>
            <li><a href="">物流管理</a> </li>
        </shiro:hasRole>
        <shiro:hasRole name="shper">
            <li><a href="">终极格式化</a> </li>
        </shiro:hasRole>
    </ul>
</body>
</html>

4.配置文件

spring.application.name=shiro
server.servlet.context-path=/shiro

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/shiro?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=hao20001010

mybatis.type-aliases-package=com.hao.springboot.entity
mybatis.mapper-locations=classpath:mapper/*.xml

logging.level.com.hao.springboot.dao=debug

5.编写mapper.xml映射文件

<?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.hao.springboot.dao.UserDao">
    <insert id="save" parameterType="User">
        insert into t_user values(#{id},#{username},#{password},#{salt})
    </insert>

    <select id="findByUserName" resultType="User">
        select * from t_user where username=#{username}
    </select>
</mapper>

6.DAO层

@Repository
public interface UserDao {

    void save(User user);

    User findByUserName(String username);
}

7.service层

public interface UserService {
    void register(User user);

    User findByUserName(String username);
}
@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;

    @Override
    public void register(User user) {
        //明文密码进行md5+salt+随机散列
        //1.生成随机盐
        String salt = SaltUtil.getSalt(8);
        //2.将随机盐保存到数据库中
        user.setSalt(salt);
        Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 1024);
        user.setPassword(md5Hash.toHex());
        userDao.save(user);
    }

    @Override
    public User findByUserName(String username) {
        return userDao.findByUserName(username);
    }
}

8.controller层

/**
 * @author:抱着鱼睡觉的喵喵
 * @date:2020/12/29
 * @description:
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;
    /**
     * 处理身份认证
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/login")
    public String login(@RequestParam("username")String username,@RequestParam("password")String password){

        //获取主体对象
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(username,password));
            return "redirect:/index.jsp";
        }catch (UnknownAccountException e){
            e.printStackTrace();
            System.out.println("用户名错误");
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            System.out.println("密码错误");
        }
        return "redirect:/login.jsp";
    }

    /**
     * 退出用户
     * @return
     */
    @RequestMapping("/outLogin")
    public String outLogin(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();           //退出用户
        return "redirect:/login.jsp";
    }

    /**
     * 用户注册
     * @return
     */
    @RequestMapping("/register")
    public String register(User user){
        try {
            userService.register(user);
            return "redirect:/login.jsp";
        }catch (Exception e){
            e.printStackTrace();
            return "redirect:/register.jsp";
        }
    }
}

9.User实体类

@Data
@ToString
@AllArgsConstructor
@Accessors(chain = true)
@NoArgsConstructor
public class User {

    private String id;
    private String username;
    private String password;
    private String salt;

}

10.创建ShiroFilter拦截器(拦截所有请求)

import com.hao.springboot.shiro.realm.CustomerRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author:抱着鱼睡觉的喵喵
 * @date:2020/12/29
 * @description:
 */
@Configuration
public class ShiroConfig {
    /**
     * 1.创建ShiroFilter
     * 负责拦截所有请求
     * @return shiroFilterFactoryBean
     */
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactory(DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //给filter设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        //配置系统首先资源
        //配置系统公共资源
        Map<String,String> map=new HashMap<>();
        map.put("/user/login","anon");       //设置为公共资源,防止登录死循环
        map.put("/user/register","anon");
        map.put("/register.jsp","anon");
        map.put("/**","authc");  //authc 这个资源需要认证和授权
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

        //默认界面路径
        shiroFilterFactoryBean.setLoginUrl("/login.jsp");
        return shiroFilterFactoryBean;
    }
    /**
     * 安全管理器
     * @return defaultWebSecurityManager
     */
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();

        defaultWebSecurityManager.setRealm(realm);
        return defaultWebSecurityManager;
    }

    /**
     *
     * @return
     */
    @Bean("realm")
    public Realm getRealm(){
        CustomerRealm customerRealm = new CustomerRealm();
        //修改凭证校验匹配器
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        //设置加密算法为md5
        credentialsMatcher.setHashAlgorithmName("MD5");
        //设置散列次数
        credentialsMatcher.setHashIterations(1024);
        customerRealm.setCredentialsMatcher(credentialsMatcher);
        return customerRealm;
    }
}

11.自定义realm

package com.hao.springboot.shiro.realm;

import com.hao.springboot.entity.User;
import com.hao.springboot.service.UserService;
import com.hao.springboot.utils.ApplicationContextUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
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.apache.shiro.util.ByteSource;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;

/**
 * @author:抱着鱼睡觉的喵喵
 * @date:2020/12/29
 * @description:    自定义realm完成用户认证和授权
 */
public class CustomerRealm extends AuthorizingRealm {
    /**
     * 用户授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("调用权限认证:"+principalCollection);
        String primaryPrincipal = (String) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        if ("Ronin".equals(primaryPrincipal)){
            simpleAuthorizationInfo.addRoles(Arrays.asList("user","admin","shaper"));
            simpleAuthorizationInfo.addStringPermission("user:add:*");
            return simpleAuthorizationInfo;
        }
//        else if("tom".equals(primaryPrincipal)){
//            simpleAuthorizationInfo.addRole("admin");
//            return simpleAuthorizationInfo;
//        }
        return null;
    }

    /**
     * 用户认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String principal = (String) authenticationToken.getPrincipal();

        //在工厂中获取业务对象
        UserService userService = (UserService) ApplicationContextUtils.getBean("userService");
        User user = userService.findByUserName(principal);
        if (!ObjectUtils.isEmpty(user)){
            return new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(), ByteSource.Util.bytes(user.getSalt()),this.getName());
        }
        return null;
    }
}

12.编写salt(因为要使用md5+salt+散列对密码加密)

package com.hao.springboot.utils;

import java.util.Random;

/**
 * @author:抱着鱼睡觉的喵喵
 * @date:2020/12/29
 * @description:
 */
public class SaltUtil {
    /**
     * 生成salt的静态方法
     * @param n
     * @return
     */
    public static String getSalt(int n){
        char[] chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()".toCharArray();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < n; i++) {
            char aChar = chars[new Random().nextInt(chars.length)];
            stringBuilder.append(aChar);
        }
        return stringBuilder.toString();
    }
//测试一下
    public static void main(String[] args) {
        System.out.println(getSalt(8));
    }
}

13.我们想要在自定义realm中的doGetAuthenticationInfo()方法调用service层,所以需要
使用静态类获取

package com.hao.springboot.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author:抱着鱼睡觉的喵喵
 * @date:2020/12/29
 * @description:
 */
@Component
public class ApplicationContextUtils implements ApplicationContextAware {

    private static ApplicationContext context;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context=applicationContext;
    }
    //
    public static Object getBean(String beanName){
        return context.getBean(beanName);
    }
}

14,测试

访问aaaa
在这f访问aaa里插入图片描述
强制到登录页面
在这里插入图片描述
以下是事先的数据
在这里插入图片描述
在这里插入图片描述
输入Ronin && 123登录
在这里插入图片描述
可以看到Ronin用户能够看所有的权限信息
接着点击退出
输入tom && 123
在这里插入图片描述
点击登录
在这里插入图片描述
可以发现tom用户什么都看不到,因为没有赋给tom用户任何权限


使用代码控制角色权限

@Controller
@RequestMapping("/limit")
public class LimitController {

    @RequestMapping("/save")
    @RequiresRoles(value = {"admin","user"})
    @RequiresPermissions("user:update:*")
    public String save(){
//        Subject subject = SecurityUtils.getSubject();
//        if (subject.hasRole("admin")) {
//            System.out.println("保存订单!");
//        }else {
//            System.out.println("无权访问");
//        }
        System.out.println("进入方法");
        return "redirect:/index.jsp";
    }
}

我从这个小案例中我学到了什么
1.使用spring框架,所有的bean都是通过容器管理的;想要使用某个组件直接从容器中拿就行了,比如service注入到controller即可;本案例中的sevice层需要被自定义的realm调用,进行密码认证,但是怎么调用就成了问题,不可能new一个吧,所有bean对象都是通过IOC容器管理的;所以那怎么办呢?我们不能直接注入service,因为bean的实例化在filter之后,因为,能力有限,以后有能力再深究吧!(Autowired底层待分析)
所以只有使用静态类,将该静态类加入容器中(使用@Component注解)

@Component
public class ApplicationContextUtils implements ApplicationContextAware {

    private static ApplicationContext context;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context=applicationContext;
    }
    //
    public static Object getBean(String beanName){
        return context.getBean(beanName);
    }
}

2.复习了ApplicationContext和BeanFactory的区别
3.shiro与springboot的整合关键在于ShiroFilter拦截器的使用
4.对于解析源码的渴望(奈何实力差太多)



以上内容只是为了记录自己的学习过程,理清自己的思路,以便以后能力更强时,不断对其补充和更改;

posted on 2020-12-29 20:06  凸凸大军的一员  阅读(147)  评论(0编辑  收藏  举报