Shiro整合Mybatis

一、导入依赖

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

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.20</version>
    </dependency>
    <!--druid连接池-->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.22</version>
    </dependency>
    <!--log4j日志-->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    <!--mybatis和springboot的整合依赖-->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.2.0</version>
    </dependency>

    <!--spring整合shiro-->
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-spring</artifactId>
        <version>1.4.1</version>
    </dependency>

    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring5</artifactId>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-java8time</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>
</dependencies>

二、添加配置文件

spring:
  datasource:
    username: root
    password: 7777
    url: jdbc:mysql://localhost:3306/emp_dept?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver

    #Spring 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:监控统计、log4j:日志记录、wall:防御sql注入
    #如果允许时报错  java.lang.ClassNotFoundException: org.apache.log4j.Priority
    #则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

#整合Mybatis
mybatis:
  type-aliases-package: com.acoffee.pojo
  mapper-locations: classpath:mapper/*.xml

三、配置SringBoot

User类(对应数据库User表)

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private int id;
    private String username;
    private String password;
}

mapper

@Repository
@Mapper
public interface UserMapper {
    User queryUserByUname(String uname);
}

UserMapper.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.acoffee.mapper.UserMapper">

    <select id="queryUserByUname" parameterType="String" resultType="User">
        select * from user where username = #{username};
    </select>
    
</mapper>

Controller层

@Controller
public class MyController {

    @RequestMapping({"/","/index"})
    public String toIndex(Model model){
        model.addAttribute("msg","hello,Shiro");
        return "index";
    }

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

    @RequestMapping("/user/update")
    public String toUpdate(){
       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);

        //执行登录的方法,如果没有异常就ok了
        //即登录成功就进入首页,登录失败就返回登录页
        try {
            subject.login(token);
            return "index";
        } catch (UnknownAccountException e) {
            model.addAttribute("msg","用户名错误");
            return "login";
        }catch (IncorrectCredentialsException e) {
            model.addAttribute("msg","密码错误");
            return "login";
        }
    }
}

Service层

UserService 接口

public interface UserService {
    User queryUserByUname(String uname);
}

UserServiceImpl (Service实现类)

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

    @Override
    public User queryUserByUname(String uname) {
        return userMapper.queryUserByUname(uname);
    }
}

四、配置Shiro

ShiroConfig 类:

@Configuration
public class ShiroConfig {

    //这三个方法环环相扣,与我们最开始那张图相对应,我们为了对应哪张图的顺序,所以在这里我们采取了这种写法
    //第三步
    //ShiroFilterFactoryBean
    //@Qualifier:Qualifier的意思是合格者,通过这个标示,表明了哪个实现类才是我们所需要的;
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("SecurityManager")DefaultSecurityManager defaultSecurityManager ){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultSecurityManager);
        /*
        * anon:无需认证就可以访问
        * authc:必须认证了才能访问
        * user:必须拥有记住我功能才能用
        * perms :拥有对某个资源的权限才能访问;
        * role:拥有某个角色权限才能访问
        * */
        Map<String, String> filterMap = new LinkedHashMap<>();

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

        //Chain:链式的,所以我们这里采用LinkedHashMap
        bean.setFilterChainDefinitionMap(filterMap);

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

        return bean;
    }

    //第二步
    //DefaultWebSecurityManager
    @Bean(name = "SecurityManager")
    public DefaultWebSecurityManager getDefaultSecurityManager(@Qualifier("userRealm")UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //第一步
    //创建Realm对象,需要自定义类
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }
}

UserRealm 类:

//自定义的需要UserRealm继承AuthorizingRealm
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了→授权doGetAuthorizationInfo");
        return null;
    }

    //认证
    //只要点登录就会走以下方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了→认证doGetAuthenticationInfo");



        //我们这个类在Controller中的login方法中被用到过,去接收用户名和密码,
        // 他是全局的所以在这里我们也能通过他去得到用户输入的用户名和密码
        UsernamePasswordToken usertoken = (UsernamePasswordToken)token;

        //连接真实的数据库
        User user = userService.queryUserByUname(usertoken.getUsername());

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


        //默认SimpleCredentialsMatcher 我们可以使用MD5加密:e10adc3949ba59abbe56e057f20f883e(123456)
        //但是因为是固定的 容易破解所以我们一般使用MD5盐值加密,
        // 例如在e10adc3949ba59abbe56e057f20f883e+username这种组合
        //密码认证,不需要我们做,shiro帮我们做,因为害怕密码泄露
        return new SimpleAuthenticationInfo("",user.getPassword(),"");

    }
}

数据库表

Shiro整合Mybatis

实现效果

登录错误的密码
Shiro整合Mybatis
显示密码错误
Shiro整合Mybatis
登录错误用户名
Shiro整合Mybatis
显示用户名错误
Shiro整合Mybatis

登录正确的
Shiro整合Mybatis
进入首页
Shiro整合Mybatis

上一篇:Spring Boot (十四): Spring Boot 整合 Shiro-登录认证和权限管理


下一篇:Shiro快速入门