shiro与springboot整合的使用
  px8Y25gMnWbQ 2023年11月02日 43 0


新建springboot项目,

shiro与springboot整合的使用_apache

 

shiro与springboot整合的使用_spring boot_02

shiro与springboot整合的使用_spring_03

导入依赖

<?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.7.16</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.shrimpking</groupId>
    <artifactId>springboot-65</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-65</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.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>
        <!-- ini整合方式的依赖       -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.9.0</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- springboot整合方式的依赖包       -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring-boot-web-starter</artifactId>
            <version>1.9.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.30</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>

mysql数据库

drop table if exists ae_user;
create table ae_user(
	id int not null auto_increment primary key comment '主键',
	username varchar(30) not null comment '用户名',
	password varchar(100) not null comment '密码',
	rid int default 0 comment '角色编号'
) comment '用户表';
insert into ae_user values (1,'zhangsan','81dc9bdb52d04dc20036dbd8313ed055','0');
insert into ae_user values (2,'lisi','81dc9bdb52d04dc20036dbd8313ed055','0');

drop table if exists ae_role;
create table ae_role(
	id int not null auto_increment primary key comment '主键',
	role_name varchar(30) not null comment '角色名称',
	`desc` varchar(50) default null comment '描述',
	real_name varchar(20) not null comment '角色显示名称'
) comment '角色表';
insert into ae_role values(1,'admin','所有权限','管理员');
insert into ae_role values(2,'userManager','用户管理权限','用户管理');

drop table if exists ae_user_role;
create table ae_user_role(
	id int not null auto_increment primary key comment '',
	user_id int not null comment '',
	role_id int not null comment ''
) comment '用户角色关系表';
insert into ae_user_role values (1,1,1);
insert into ae_user_role values (2,1,2);
insert into ae_user_role values (3,2,2);

drop table if exists ae_permission;
create table ae_permission(
	id int not null auto_increment primary key comment '主键',
	permission_name varchar(30) not null comment '权限名称',
	info varchar(50) default null comment '权限内容',
	`desc` varchar(50) default null comment '描述'
) comment '权限表';
insert into ae_permission values (1,'删除用户','user:delete','删除全部用户');
insert into ae_permission values (2,'新增用户','user:add','增加一个用户');
insert into ae_permission values (3,'编辑用户','user:edit','编辑一个用户');

drop table if exists ae_role_permission;
create table ae_role_permission(
	id int not null auto_increment primary key comment '',
	role_id int not null comment '',
	permission_id int not null comment ''
) comment '权限表';
insert into ae_role_permission values (1,1,1);
insert into ae_role_permission values (2,1,2);
insert into ae_role_permission values (3,1,3);

select 
r.role_name
from ae_role as r
left join ae_user_role as ur on ur.role_id = r.id
left join ae_user as u on u.id = ur.user_id
where u.username = 'zhangsan'

select 
p.info
from ae_permission as p 
left join ae_role_permission as rp on rp.permission_id = p.id
left join ae_role as r on r.id = rp.role_id
left join ae_user_role as ur on ur.role_id = r.id
left join ae_user as u on u.id = ur.user_id
where u.username = 'zhangsan'

ini方式

shiro.ini

[main]
md5CredentialsMatcher=org.apache.shiro.authc.credential.Md5CredentialsMatcher
#此项是配置加盐次数的md5CredentialsMatcher.hashIterations=3

myrealm=com.shrimpking.realm.MyRealm
myrealm.credentialsMatcher=$md5CredentialsMatcher
securityManager.realms=$myrealm


[users]
zhangsan=81dc9bdb52d04dc20036dbd8313ed055,role1,role2
lisi=1234

[roles]
role1:user:insert,user:select

myrealm.java

package com.shrimpking.realm;

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.realm.AuthenticatingRealm;
import org.apache.shiro.util.ByteSource;

import javax.print.DocFlavor;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/9/30 11:39
 */
public class MyRealm extends AuthenticatingRealm
{
    /**
     * 自定义的认证登录方法,shiro的login方法的底层调用此类的认证方法进行认证
     * 需要配置自定义的realm生效,在ini文件中配置,在springboot中配置
     * 此方法只是获取需要验证的信息
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException
    {
        //获取身份信息
        String principal = authenticationToken.getPrincipal().toString();
        //获取凭证信息
        String password  = new String((char[]) authenticationToken.getCredentials());
        System.out.println("身份信息=" + principal);
        System.out.println("密码=" + password);
        System.out.println(getName());
        //访问数据库获取用户信息
        if(principal.equals("zhangsan")){
            //从数据库查询加密的密码
            String pwdInfo = "81dc9bdb52d04dc20036dbd8313ed055";
            //封装到校验的逻辑对象中
            AuthenticationInfo info = new SimpleAuthenticationInfo(
                    authenticationToken.getPrincipal(),
                    pwdInfo,
                    ByteSource.Util.bytes(""),
                    getName()
            );
            return info;
        }
        return null;
    }
}

shiroMd5.java

package com.shrimpking;

import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.swing.plaf.SliderUI;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/9/30 11:01
 */
@SpringBootTest
public class ShiroMD5
{

    @Test
    public void test(){
        //密码明文
        String password = "1234";
        //使用md5加密
        Md5Hash md5Hash1 = new Md5Hash(password);
        System.out.println("使用md5加密 = " + md5Hash1);
        //使用md5加密 = 81dc9bdb52d04dc20036dbd8313ed055

        //带盐的md5加密
        String salt = "salt";
        Md5Hash md5Hash2 = new Md5Hash(password,salt);
        System.out.println("带盐的加密 = " +md5Hash2);
        //带盐的加密 = a6d4f0a9c109cd24eacb88e75e5be690

        //带盐的3次md5加密
        Md5Hash md5Hash3 = new Md5Hash(password,salt,3);
        System.out.println("带盐的3次加密 = " + md5Hash3);
        //带盐的3次加密 = 3eb72410276a5e43764a2722874c27c6

        //使用父类加密
        SimpleHash simpleHash = new SimpleHash("MD5",password,salt,3);
        System.out.println("使用父类加密 = " + simpleHash);
        //使用父类加密 = 3eb72410276a5e43764a2722874c27c6

    }
}

shiroTest.java

package com.shrimpking;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/9/30 10:22
 */
@SpringBootTest
public class ShiroTest
{
    @Test
    public void test(){
        //获取securityManager
        IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        //获取subject对象
        Subject subject = SecurityUtils.getSubject();
        //创建token
        AuthenticationToken token = new UsernamePasswordToken("zhangsan", "1234");
        //完成登录
        try
        {
            subject.login(token);
            System.out.println("登录成功");
            //判断角色是否存在
            boolean hasRole = subject.hasRole("role1");
            System.out.println("是否拥有此角色=" +hasRole);
            //判断权限
            boolean permitted = subject.isPermitted("user:insert");
            System.out.println("是否拥有此权限=" + permitted);
            try
            {
                subject.checkPermission("user:delete");
            }
            catch (AuthorizationException e)
            {
                System.out.println("无权限");
            }
        }
        catch (UnknownAccountException e){
            e.printStackTrace();
            System.out.println("用户不存在");
        }
        catch (IncorrectCredentialsException e){
            e.printStackTrace();
            System.out.println("密码错误");
        }
        catch (AuthenticationException e)
        {
            e.printStackTrace();
        }

    }
}

springboot整合方式

配置

application.properties

server.port=8089

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimeZone=UTC
spring.datasource.username=root
spring.datasource.password=mysql123
#日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#配置别名
mybatis-plus.type-aliases-package=com.shrimpking.pojo
#日期格式化
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone= GMT+8
#
shiro.loginUrl=/testController/toLogin

pojo

user.java

package com.shrimpking.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/9/30 12:50
 */
@Data
@TableName("ae_user")
public class User
{
    @TableId(value = "id",type = IdType.AUTO)
    private Integer id;
    private String username;
    private String password;
    private Integer rid;
}

mapper

userMapper.java

package com.shrimpking.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.shrimpking.pojo.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/9/30 12:55
 */
public interface UserMapper extends BaseMapper<User>
{
    List<String> getUserRoleInfoByName(@Param("username") String username);
    List<String> getUserPermissionInfoByName(@Param("username") String username);
}

mapperxml

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.shrimpking.mapper.UserMapper">
    <!-- 根据用户名查询权限名称列表   -->
    <select id="getUserRoleInfoByName" resultType="java.lang.String">
        select
        r.role_name
        from ae_role as r
        left join ae_user_role as ur on ur.role_id = r.id
        left join ae_user as u on u.id = ur.user_id
        where u.username = #{username}
    </select>
    <!-- 根据用户名查询权限名称列表   -->
    <select id="getUserPermissionInfoByName" resultType="java.lang.String">
        select
        p.info
        from ae_permission as p
        left join ae_role_permission as rp on rp.permission_id = p.id
        left join ae_role as r on r.id = rp.role_id
        left join ae_user_role as ur on ur.role_id = r.id
        left join ae_user as u on u.id = ur.user_id
        where u.username = #{username}
    </select>

</mapper>

service

userservice.java

package com.shrimpking.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.shrimpking.pojo.User;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/9/30 12:56
 */
public interface UserService extends IService<User>
{
    //用户登录
    User getUserByUserName(String username);

    //根据用户名查询权限名称列表
    List<String> getUserRoleInfo(String username);

    //根据用户名获取权限名称列表
    List<String> getUserPermisstionInfo(String username);
}

serviceimpl

userserviceimpl.java

package com.shrimpking.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shrimpking.mapper.UserMapper;
import com.shrimpking.pojo.User;
import com.shrimpking.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/9/30 12:57
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService
{
    @Autowired
    private UserMapper userMapper;

    @Override
    public User getUserByUserName(String username)
    {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,username);
        List<User> userList = this.userMapper.selectList(queryWrapper);
        return userList.get(0);
    }

    @Override
    public List<String> getUserRoleInfo(String username)
    {
        return this.userMapper.getUserRoleInfoByName(username);
    }

    @Override
    public List<String> getUserPermisstionInfo(String username)
    {
        return this.userMapper.getUserPermissionInfoByName(username);
    }

}

controller

testcontroller.java

package com.shrimpking.controller;

import com.sun.xml.internal.ws.resources.HttpserverMessages;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/9/30 14:42
 */
@Controller
@RequestMapping("/testController")
public class TestController
{
    @GetMapping("/userLogin")
    //@ResponseBody
    public String userLogin(
            @RequestParam("name") String username,
            @RequestParam("pwd") String password,
            @RequestParam(defaultValue = "false",value = "rememberMe") boolean rememberMe,
            HttpSession session){
        //获取subject对象
        Subject subject = SecurityUtils.getSubject();
        //封装请求数据到token对象中
        AuthenticationToken token = new UsernamePasswordToken(username,password,rememberMe);
        //完成登录
        try
        {
            subject.login(token);
            session.setAttribute("user",token.getPrincipal().toString());
            return "main";
            //return "登录成功";
            //http://localhost:8089/testController/userLogin?name=zhangsan&pwd=1234
        }
        catch (AuthenticationException e)
        {
            e.printStackTrace();
            System.out.println("登录失败");
            return "登录失败";
        }
        //
    }

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

    @GetMapping("/userLoginRm")
    public String userLoginRm(HttpSession session){
        session.setAttribute("user","rememberMe");
        return "main";
    }

    //验证角色
    @RequiresRoles("admin")
    @GetMapping("/userLoginRoles")
    @ResponseBody
    public String userLoginRoles(){
        System.out.println("验证角色");
        return "验证角色成功";
    }

    //验证权限
    @RequiresPermissions("user:delete")
    @GetMapping("/userLoginPermission")
    @ResponseBody
    public String userLoginPermission(){
        System.out.println("验证权限");
        return "验证权限成功";
    }

}

 permissionException.java

package com.shrimpking.controller;

import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/9/30 18:58
 */
@ControllerAdvice
public class PermissionException
{
    @ResponseBody
    @ExceptionHandler(UnauthorizedException.class)
    public String unauthorizedException(Exception e){
        System.out.println(e.getMessage());
        return "无权限";
    }

    @ResponseBody
    @ExceptionHandler(UnauthenticatedException.class)
    public String unauthenticatedException(Exception e){
        System.out.println(e.getMessage());
        return "权限验证失败";
    }

}

new  myrealm

myrealm.java

package com.shrimpking.newrealm;

import com.shrimpking.pojo.User;
import com.shrimpking.service.UserService;
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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/9/30 14:15
 */
@Component
public class MyRealm extends AuthorizingRealm
{
    @Autowired
    private UserService userService;

    /**
     * 自定义授权方法
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection)
    {
        System.out.println("自定义授权");
        //获取用户身份信息
        String username = principalCollection.getPrimaryPrincipal().toString();
        //获取角色信息
        List<String> roleNameList = this.userService.getUserRoleInfo(username);
        System.out.println("当前用户角色信息 =" + roleNameList);
        //获取权限信息
        List<String> permissionList = this.userService.getUserPermisstionInfo(username);
        System.out.println("当前用户权限信息=" + permissionList);
        //创建对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //存储角色
        //info.addRole("admin");
        info.addRoles(roleNameList);
        info.addStringPermissions(permissionList);
        //返回
        return info;
    }

    /**
     * 自定义登录认证方法
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException
    {
        //获取用户身份信息
        String username = authenticationToken.getPrincipal().toString();
        //调用业务层,获取数据库的用户信息
        User user = this.userService.getUserByUserName(username);
        //非空判断,将数据封装返回
        if(user != null){
            AuthenticationInfo info = new SimpleAuthenticationInfo(
                    authenticationToken.getPrincipal(),
                    user.getPassword(),
                    ByteSource.Util.bytes(""),
                    getName()
            );
            return info;
        }

        return null;
    }
}

config

shrioconfig.java

package com.shrimpking.config;

import com.shrimpking.newrealm.MyRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authc.pam.AllSuccessfulStrategy;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import sun.security.krb5.Realm;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2023/9/30 14:25
 * shiro配置类
 */
@Configuration
public class ShiroConfig
{
    @Autowired
    private MyRealm myRealm;

    /**
     * 安全管理器
     * @return
     */
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(){
        //创建defaultWebSecurityManager对象
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//        //多realm策略
//        ModularRealmAuthenticator authenticator = new ModularRealmAuthenticator();
//        //全部通过策略
//        authenticator.setAuthenticationStrategy(new AllSuccessfulStrategy());
//        //
//        securityManager.setAuthenticator(authenticator);
//        List<Realm> realmList = new ArrayList<>();
//        realmList.add(myRealm);
//        securityManager.setRealms(realmList);

        //创建加密对象
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        //采用md5加密
        credentialsMatcher.setHashAlgorithmName("MD5");
        //迭代加密次数
        credentialsMatcher.setHashIterations(1);
        //将加密对象,存储到myrealm中
        myRealm.setCredentialsMatcher(credentialsMatcher);
        //将myrealm,存到securityManager中
        securityManager.setRealm(myRealm);
        //设置rememberMe
        securityManager.setRememberMeManager(cookieRememberMeManager());
        //开始session
        //securityManager.setSessionManager(new DefaultWebSessionManager());
        //返回
        return securityManager;
    }

    /**
     * shiro的内置拦截器
     * @return
     */
    @Bean
    public DefaultShiroFilterChainDefinition defaultShiroFilterChainDefinition(){
        DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition();
        //设置不认证可以访问的路径
        definition.addPathDefinition("/testController/userLogin","anon");
        definition.addPathDefinition("/testController/toLogin","anon");
        //设置需要退出系统的路径
        definition.addPathDefinition("/logout","logout");
        //设置需要认证才可以访问的路径
        definition.addPathDefinition("/**","authc");
        //设置rememberMe
        definition.addPathDefinition("/**","user");
        return definition;
    }

    /**
     * rememberMe的cookie配置
     * @return
     */
    public CookieRememberMeManager cookieRememberMeManager(){
        CookieRememberMeManager manager = new CookieRememberMeManager();
        SimpleCookie cookie = new SimpleCookie("rememberMe");
        cookie.setPath("/");
        cookie.setHttpOnly(true);
        cookie.setMaxAge(30*24*60*60);
        manager.setCookie(cookie);
        //manager.setCipherKey("1234567890".getBytes());
        return manager;
    }
}

templates

login.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"/>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>shiro登录验证</title>
</head>
<body>
    <h1>shiro登录</h1>
    <form action="/testController/userLogin">
        <label for="name">账号:</label>
        <input type="text" name="name" id="name" value="">
        <br>
        <label for="pwd">密码:</label>
        <input type="password" name="pwd" id="pwd" value="">
        <br>
        <label for="rememberMe">记住我</label>
        <input type="checkbox" name="rememberMe" id="rememberMe" value="true">
        <br>
        <input type="submit" value="登录">
    </form>
</body>
</html>

main.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"/>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录后首页</title>
</head>
<body>
    <h1>shiro登录认证成功后页面</h1>
    <br>
    登录用户为: <p th:text="${ session.user }"></p>
    <a href="/logout">退出</a>
    <br>
    <a href="/testController/userLoginRoles">验证授权-角色</a>
    <br>
    <a href="/testController/userLoginPermission">验证授权-权限</a>
</body>
</html>

测试

登录

shiro与springboot整合的使用_spring_04

shiro与springboot整合的使用_spring_05

登录成功后

shiro与springboot整合的使用_java_06

 验证角色

shiro与springboot整合的使用_spring boot_07

 验证权限

shiro与springboot整合的使用_spring boot_08

 记住我

shiro与springboot整合的使用_spring boot_09

 

shiro与springboot整合的使用_后端_10

 

shiro与springboot整合的使用_apache_11

 无权限

shiro与springboot整合的使用_spring_12

 

shiro与springboot整合的使用_java_13

 

shiro与springboot整合的使用_apache_14

 

shiro与springboot整合的使用_spring boot_15

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  xaeiTka4h8LY   2024年05月17日   52   0   0 数据库JavaSQL
px8Y25gMnWbQ