SpringBoot之----了解Shiro安全框架整合Mybatis和thymeleaf,实现授权登陆认证

这里我做一个流程图帮助大家理解Shiro安全框架整合Mybatis和thymeleaf,实现授权登陆认证的过程,大家先了解,然后看代码,看完代码再看流程图。

SpringBoot之----了解Shiro安全框架整合Mybatis和thymeleaf,实现授权登陆认证_第1张图片

1.了解完那我们先看项目结构:

项目结构:
SpringBoot之----了解Shiro安全框架整合Mybatis和thymeleaf,实现授权登陆认证_第2张图片
数据库截图:
SpringBoot之----了解Shiro安全框架整合Mybatis和thymeleaf,实现授权登陆认证_第3张图片

2.我们再看整个项目的代码:

pom.xml


<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.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.6.2version>
        <relativePath/> 
    parent>
    <groupId>com.wlmgroupId>
    <artifactId>shiro-springbootartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>shiro-springbootname>
    <description>Demo project for Spring Bootdescription>
    <properties>
        <java.version>1.8java.version>
    properties>
    <dependencies>

        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
        <dependency>
            <groupId>log4jgroupId>
            <artifactId>log4jartifactId>
            <version>1.2.17version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.1.9version>
        dependency>
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>2.1.1version>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
        dependency>
        
        <dependency>
            <groupId>com.github.theborakompanionigroupId>
            <artifactId>thymeleaf-extras-shiroartifactId>
            <version>2.0.0version>
        dependency>
        
        <dependency>
            <groupId>org.apache.shirogroupId>
            <artifactId>shiro-springartifactId>
            <version>1.4.1version>
        dependency>
        <dependency>
            <groupId>org.apache.shirogroupId>
            <artifactId>shiro-coreartifactId>
            <version>1.4.1version>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-thymeleafartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>

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

project>

application.yml

spring:
  datasource:
    username: root
    password: admin
    url: jdbc:mysql://localhost:3306/wuting?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource # 自定义数据源

    #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

application.properties

mybatis.type-aliases-package=com.wlm.pojo
mybatis.mapper-locations=classpath:mapper/*.xml

login.html

DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
<h1>登陆h1>
<hr>
<p th:text="${msg}" style="color: red">p>
<form th:action="@{/login}">
    <p>账  号:<input type="text" name="username">p>
    <p>密  码:<input type="text" name="password">p>
    <p><input type="submit">p>
form>
body>
html>

index.html

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>Titletitle>
head>
<body>

<h1>首页h1>

<div th:if="${session.loginUser==null}">
    <a th:href="@{/toLogin}">登陆a>
div>
<p th:text="${msg}">p>
<hr>
<div shiro:hasPermission="user:add">
    <a th:href="@{/user/add}">adda>
div>
<div shiro:hasPermission="user:update">
    <a th:href="@{/user/update}">updatea>
div>
body>
html>

update.html

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>

<h1>updateh1>

body>
html>

add.html

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>

<h1>addh1>

body>
html>

UserMapper.xml


DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.wlm.mapper.UserMapper">
    
    <select id="queryUserByName" resultType="User" parameterType="String">
        select * from wuting.wt where username = #{username}
    select>

mapper>

ShiroConfig.java

package com.wlm.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
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注解主要是给我们的类加上了cglib代理。
//在执行我们的配置类的方法时,会执行cglib代理类中的方法
@Configuration
public class ShiroConfig {
    //shiroFilterFactoryBean:第三步
    @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<>();

        //授权,正常的情况下,没有授权会跳到未授权页面
        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;
    }
    //DefaultWebSecurityManager:第二步
    @Bean(name="securityManager")
    public DefaultWebSecurityManager getdefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联userRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //创建realm对象:第一步
    @Bean
    public UserRealm userRealm(){
        //需要自定义,交给spring托管
        return new UserRealm();
    }
    //整合ShiroDialect:用来整合shiro thymeleaf
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}

UserRealm.java

package com.wlm.config;

import com.wlm.pojo.User;
import com.wlm.service.UserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

//自定义的 UserRealm,继承AuthorizingRealm,然后重写授权和认证方法,跟SpringSecurity很像的。
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserServiceImpl userService;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("doGetAuthorizationInfo授权=》咸鱼_翻身");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //info.addStringPermission("user:add");
        //拿到当前登陆的这个对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();
        //设置当前用户的权限
        info.addStringPermission(currentUser.getPerms());
        return info;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("doGetAuthenticationInfo认证=》咸鱼_翻身");

        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做就好了
        //我们得知道他是MD5加密或者MD5盐值加密的(盐值加密就是在MD5的基础上面加一些用户信息)
        return new SimpleAuthenticationInfo( user,user.getPassword(),"");
    }
}

MyController.java

package com.wlm.controller;

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.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {

    @RequestMapping({"/","/index"})
    public String toIndex(Model model){
        model.addAttribute("msg","hello xian_yu");
        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);
            return "index";
        }catch (UnknownAccountException e){//用户名不存在
            model.addAttribute("msg","用户名错误");
            return "login";
        }catch (IncorrectCredentialsException e){//密码不存在
            model.addAttribute("msg","密码错误");
            return "login";
        }
    }

    @RequestMapping("/noauth")
    @ResponseBody
    public String unauthorized(){
        return "没有授权,无法访问当前页面";
    }

}

UserMapper接口

package com.wlm.mapper;

import com.wlm.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

@Repository
@Mapper
public interface UserMapper {
    public User queryUserByName(String name);
}

User.java

package com.wlm.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

    private int id;
    private String username;
    private String password;
    private String perms;

}

UserService接口

package com.wlm.service;

import com.wlm.pojo.User;

public interface UserService {
    public User queryUserByName(String name);
}

UserServiceImpl.java

package com.wlm.service;

import com.wlm.mapper.UserMapper;
import com.wlm.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

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

3.运行结果:

点击登陆:
SpringBoot之----了解Shiro安全框架整合Mybatis和thymeleaf,实现授权登陆认证_第4张图片
那么输入我们数据库设计好的账号:wt 密码:123456 点击提交:
SpringBoot之----了解Shiro安全框架整合Mybatis和thymeleaf,实现授权登陆认证_第5张图片
不难看出,这里只显示了add,说明某些用户获取的权限和看到界面就是给过滤过的,点击add就能看见我们写好给规定用户看的了:
SpringBoot之----了解Shiro安全框架整合Mybatis和thymeleaf,实现授权登陆认证_第6张图片
SpringBoot之----了解Shiro安全框架整合Mybatis和thymeleaf,实现授权登陆认证_第7张图片
那么我们换一个账号密码呢?账号:xian_yu 密码 123456
SpringBoot之----了解Shiro安全框架整合Mybatis和thymeleaf,实现授权登陆认证_第8张图片
当然我们也只能看见update界面的东西:
SpringBoot之----了解Shiro安全框架整合Mybatis和thymeleaf,实现授权登陆认证_第9张图片
SpringBoot之----了解Shiro安全框架整合Mybatis和thymeleaf,实现授权登陆认证_第10张图片
这时候我们再去返回首页就能看见首页变成我们的update了:
SpringBoot之----了解Shiro安全框架整合Mybatis和thymeleaf,实现授权登陆认证_第11张图片

你可能感兴趣的:(Java,spring,boot,spring,boot,安全,java)