SpringBoot整合Shiro和SSM(完成认证和授权效果)

SpringBoot整合Shiro

这一部分写在另一篇博客,这里主要是讲Mybatis的整合
当然,如果不看SpringBoot整合Shiro也可以,只看这篇博客也会自然而然地把SpringBoot整合进去,就是关于SpringBoot整合Shiro笔记不会很详细
本篇博客的源码科在码云直接下载

项目整体结构如下

在这里插入图片描述

添加依赖

pom.xml

<?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.2.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>springboot_shiro_mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot_shiro_mybatis</name>
    <description>SpringBoot整合Shiro和Mybatis</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!--添加mybatis启动器,jdbc支持,mysql驱动,log4j日志和druid的依赖-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.21</version>
        </dependency>

        <!--SpringBoot整合shiro的依赖-->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.5.2</version>
        </dependency>

        <!--thymeleaf-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!--添加nekohtml依赖的原因是我不想使用严格的HTML5标准(每个标签都是一对的),加入这个依赖后就可以使用不严格的了-->
        <dependency>
            <groupId>net.sourceforge.nekohtml</groupId>
            <artifactId>nekohtml</artifactId>
            <version>1.9.22</version>
        </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>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

比SpringBoot整合Shiro多了5个依赖

<!--添加mybatis启动器,jdbc支持,mysql驱动,log4j日志和druid的依赖-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.21</version>
        </dependency>

编写application配置文件

application.yml

spring:
  thymeleaf:
    cache: false
    mode: LEGACYHTML5 #为了使用不严格的w3c标准,不然很麻烦
    encoding: utf-8
    servlet:
      content-type: text/html
  datasource:
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/spring_boot?serverTimezone=UTC
    type: com.alibaba.druid.pool.DruidDataSource
    filters: stat,wall


mybatis:
  type-aliases-package: com.example.springboot_shiro_mybatis.substance
  mapper-locations: classpath:mybatis/mapper/*

创建一个简单的数据库

在这里插入图片描述
并且创建对应的实体类
Student.java

package com.example.springboot_shiro_mybatis.substance;

public class Student {
    private String id;
    private String name;
    private int age;
    private String password;

    public String getId() {
        return id;
    }

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

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

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

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public Student(String id, String name, int age, String password) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.password = password;
    }
}

创建Mapper.xml文件

在这里插入图片描述
StudentMapper.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.example.springboot_shiro_mybatis.mapper.StudentMapper">
    <select id="queryStudent" resultType="com.example.springboot_shiro_mybatis.substance.Student" parameterType="String">
        select * from student where name=#{name} limit 1
    </select>
</mapper>

前端页面

和之前SpringBoot整合Shiro的前端页面无太大差别别,就多了一个未授权和delete页面
在这里插入图片描述

index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>Welcome</h1>
<a th:href="@{/user/add}">add</a>
<a th:href="@{/user/update}">update</a>
<a th:href="@{/user/delete}">delete</a>
</body>
</html>

login.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登陆</title>
</head>
<body>
<p th:text="${{tips}}"></p>
<form th:action="@{/login}">
    账号<input name="username"><br>
    密码<input type="password" name="userpwd"><br>
    <input type="submit" value="登陆">
</form>
</body>
</html>

随便写一个<p></p>标签的update.html,add.htmldelete.html

SSM三层的代码

indexController

package com.example.springboot_shiro_mybatis.controller;

import com.example.springboot_shiro_mybatis.service.IQueryStudent;
import com.example.springboot_shiro_mybatis.substance.Student;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
public class indexController {
    @Autowired
    IQueryStudent queryUserId;
    @RequestMapping({"/","index.html"})
    public String toIndex(Model model){
        model.addAttribute("tips","Hello Shiro");
        return "index";
    }

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

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

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


    @RequestMapping("/login")
    public String login(String username,String userpwd,Model model){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, userpwd);
        try {
            System.out.println("切到UserRealm");
            subject.login(token);//执行登陆
            System.out.println("从UserRealm切换回来");
            return "index";
        }catch (UnknownAccountException e){
            model.addAttribute("tips","用户名异常");
            return "login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("tips","密码错误");
            return "login";
        }
    }
    @RequestMapping("/Unauthorized")
    public String Unauthorized(){
        return "Unauthorized";
    }
}

IQueryStudent

package com.example.springboot_shiro_mybatis.service;
import com.example.springboot_shiro_mybatis.substance.Student;
import java.util.List;

public interface IQueryStudent {
    Student querryStudent(String name);
}

QueryUserIdImp

package com.example.springboot_shiro_mybatis.service.serviceImp;

import com.example.springboot_shiro_mybatis.mapper.StudentMapper;
import com.example.springboot_shiro_mybatis.service.IQueryStudent;
import com.example.springboot_shiro_mybatis.substance.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class QueryUserIdImp implements IQueryStudent {

    @Autowired
    StudentMapper studentMapper;

    @Override
    public Student querryStudent(String name) {
        Student student = studentMapper.queryStudent(name);
        return student;
    }
}

StudentMapper

package com.example.springboot_shiro_mybatis.mapper;

import com.example.springboot_shiro_mybatis.substance.Student;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;


@Mapper
@Repository
public interface StudentMapper {
    Student queryStudent(String name);//查询所有学生
}

Shiro配置类

UserRealm

package com.example.springboot_shiro_mybatis.config;

import com.example.springboot_shiro_mybatis.service.IQueryStudent;
import com.example.springboot_shiro_mybatis.substance.Student;
import org.apache.catalina.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    IQueryStudent queryUserId;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("UserReal进行授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取当前用户
        Subject subject = (Subject) SecurityUtils.getSubject();
        //获取用户信息
        Student student = (Student) subject.getPrincipal();
        //再此处为了方便,我将id为1的用户给予访问delete的权限
        if("1".equals(student.getId())) {
            info.addStringPermission("user:delete");
        }
        return info;
    }

    //认证,点击登陆就会执行该方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("UserReal进行认证");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        Student student = queryUserId.querryStudent(token.getUsername());
        if(student == null){
            return null;
        }
        //此处是为了学习SpringBoot,Shiro与Mybatis的整合,所以就没有进行密码加密,一般常用的有md5和md5盐值加密
        //密码认证直接交给Shiro即可
        return new SimpleAuthenticationInfo("",student.getPassword(),"");//注意这里的密码放的是正确的密码
    }
}

ShiroConfig

package com.example.springboot_shiro_mybatis.config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    //创建realm对象
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }

    //创建DefaultWebSecurityManager也就是securityManager,并将其与UserRealm关联起来
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm")UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联userRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //创建ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager securityManager ){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(securityManager);
        //设置shiro的内置过滤器
        /*
            anon:无需认证就可以访问
            authc:无需认证就可以访问
            usser:必须用有记住我功能该可以访问
            perms:拥有某个资源的权限才可以启动,注意:这里说的是资源而不是角色
            role:拥有某个角色权限开可以访问
         */

        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/user/add","anon");//无需登录就可以进去
        filterMap.put("/user/update","authc");//需要登陆才可以进去
        filterMap.put("/user/delete","perms[user:delete]");//登陆后有对应地权限才可以进去
        //通配符写法,拦截所有请求 filterMap.put("/**","authc");

        bean.setFilterChainDefinitionMap(filterMap);
        //设置登陆请求
        bean.setLoginUrl("/toLogin");
        // 登录成功请求
        bean.setSuccessUrl("/index");
        return bean;
    }
}

完成

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值