目录

一、📢前言 

二、📝SpringBoot整合Shiro

2.1 📲导入依赖

2.2.🚩创建实体

2.3 📌配置Shiro

2.4 📌编写CustomRealm

2.5 🏮编写相关的接口

2.6🔑业务实现代码

三.🖍️测试:

四、📚参考文献


一、📢前言 

🚩1.1 什么是Shiro
Shiro是一个开源的Java安全框架,它提供了身份认证、授权、加密和会话管理等功能,可以帮助我们快速地构建安全可靠的应用程序。

🚩1.2 为什么要用Shiro
在开发Web应用程序时,安全性是一个非常重要的问题。使用Shiro可以帮助我们快速地构建安全可靠的应用程序,而且Shiro的使用非常灵活,可以根据我们的需求进行定制。

二、📝SpringBoot整合Shiro

🏘️项目结构
🍒bean
    Permissions
    Role
    User
🍒config
    shiroConfig
🍒controller
    LoginController
🍒handler
    MyExceptionHandler
🍒service
    impl
      LoginServiceImpl
    LoginService
🍒shiro
    CustomRealm

2.1 📲导入依赖

 <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.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.11.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</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>
    </dependencies>
  • spring-boot-starter-web:提供Web应用程序所需的核心Spring Boot依赖项。
  • spring-boot-devtools:提供开发工具,例如自动重新加载和远程调试。
  • shiro-spring:提供Apache Shiro安全框架的Spring集成
  • spring-boot-starter-thymeleaf:提供Thymeleaf模板引擎。
  • lombok:提供Java注解,简化了Java代码的编写。
  • spring-boot-starter-test:提供Spring Boot测试框架所需的依赖项。

2.2.🚩创建实体

   2.2.1 Permissions.java

import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class Permissions {
    private String id;
    private String permissionsName;
}

2.2.2.Role.java

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.Set;

@Data
@AllArgsConstructor
public class Role {

    private String id;
    private String roleName;
    /**
     * 角色对应权限集合
     */
    private Set<Permissions> permissions;
}

2.2.3. User.java

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.Set;

@Data
@AllArgsConstructor
public class User {
    private String id;
    private String userName;
    private String password;
    /**
     * 用户对应的角色集合
     */
    private Set<Role> roles;
}

2.3 📌配置Shiro

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: lidh
 * @Date: 2023/04/17/22:07
 * @Description:
 */
@Configuration
public class shiroConfig {

    @Bean
    @ConditionalOnMissingBean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator defaultAAP = new DefaultAdvisorAutoProxyCreator();
        defaultAAP.setProxyTargetClass(true);
        return defaultAAP;
    }

    //将自己的验证方式加入容器
    @Bean
    public CustomRealm myShiroRealm() {
        CustomRealm customRealm = new CustomRealm();
        return customRealm;
    }

    //权限管理,配置主要是Realm的管理认证
    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(myShiroRealm());
        return securityManager;
    }

    //Filter工厂,设置对应的过滤条件和跳转条件
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        Map<String, String> map = new LinkedHashMap<>();
        //登出
        map.put("/logout", "logout");
        //对所有用户认证
//        map.put("/index", "anon");
        map.put("/**", "authc");

        //登录
        shiroFilterFactoryBean.setLoginUrl("/login");
        //首页
        shiroFilterFactoryBean.setSuccessUrl("/index");
        //错误页面,认证不通过跳转
        shiroFilterFactoryBean.setUnauthorizedUrl("/error");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        return shiroFilterFactoryBean;
    }


    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
}
  • @Configuration:标识该类为Java配置类。
  • defaultAdvisorAutoProxyCreator():配置Shiro的自动代理创建器,用于自动代理所有Advisor。
  • myShiroRealm():将自定义的Realm加入容器中,用于Shiro的认证和授权
  • securityManager():配置Shiro的安全管理器,主要是配置Realm的管理认证。
  • shiroFilterFactoryBean():配置Shiro的过滤器工厂,用于设置过滤条件和跳转条件。
  • authorizationAttributeSourceAdvisor():配置Shiro的授权属性源顾问,用于获取授权信息。

各个方法都使用了@Bean注解,表示将该方法返回的对象加入Spring容器中,供其他组件使用。

2.4 📌编写CustomRealm

import com.example.demo.bean.Permissions;
import com.example.demo.bean.Role;
import com.example.demo.bean.User;
import com.example.demo.service.LoginService;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: lidh
 * @Date: 2023/04/17/22:11
 * @Description:
 */
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private LoginService loginService;

    /**
     * @MethodName doGetAuthorizationInfo
     * @Description 权限配置类
     * @Param [principalCollection]
     * @Return AuthorizationInfo
     * @Author WangShiLin
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取登录用户名
        String name = (String) principalCollection.getPrimaryPrincipal();
        //查询用户名称
        User user = loginService.getUserByName(name);
        //添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for (Role role : user.getRoles()) {
            //添加角色
            simpleAuthorizationInfo.addRole(role.getRoleName());
            //添加权限
            for (Permissions permissions : role.getPermissions()) {
                simpleAuthorizationInfo.addStringPermission(permissions.getPermissionsName());
            }
        }
        return simpleAuthorizationInfo;
    }

    /**
     * @MethodName doGetAuthenticationInfo
     * @Description 认证配置类
     * @Param [authenticationToken]
     * @Return AuthenticationInfo
     * @Author WangShiLin
     * @return
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        if (StringUtils.isEmpty((String) authenticationToken.getPrincipal())) {
            return null;
        }
        //获取用户信息
        String name = authenticationToken.getPrincipal().toString();
        User user = loginService.getUserByName(name);
        if (user == null) {
            //这里返回后会报出对应异常
            return null;
        } else {
            //这里验证authenticationToken和simpleAuthenticationInfo的信息
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(name, user.getPassword().toString(), getName());
            return simpleAuthenticationInfo;
        }
    }
}

📊这是一个自定义的Shiro Realm类,用于实现Shiro的认证和授权。该类继承了AuthorizingRealm类,实现了doGetAuthenticationInfo()和doGetAuthorizationInfo()方法。

  • 📍doGetAuthenticationInfo()方法:用于处理Shiro的认证,验证用户的身份和凭证是否正确。
  • 📍doGetAuthorizationInfo()方法:用于处理Shiro的授权,获取用户的角色和权限信息。

该类中使用了@Autowired注解,注入了LoginService类,用于获取用户的信息。在处理认证和授权时,通过调用LoginService类中的方法获取用户的信息,并根据角色和权限信息进行认证和授权。

在处理授权时,该类使用了SimpleAuthorizationInfo类,用于添加角色和权限信息。在处理认证时,该类使用了SimpleAuthenticationInfo类,用于验证用户的身份和凭证是否正确。

2.5 🏮编写相关的接口

import com.example.demo.bean.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class LoginController {

    //http://localhost:8080/login?userName=zhangsan&password=123456
    @GetMapping("/login")
    public String login(User user) {
        if (StringUtils.isEmpty(user.getUserName()) || StringUtils.isEmpty(user.getPassword())) {
            return "请输入用户名和密码!";
        }
        //用户认证信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                user.getUserName(),
                user.getPassword()
        );
        try {
            //进行验证,这里可以捕获异常,然后返回对应信息
            subject.login(usernamePasswordToken);
//            subject.checkRole("admin");
//            subject.checkPermissions("query", "add");
        } catch (UnknownAccountException e) {
            log.error("用户名不存在!", e);
            return "用户名不存在!";
        } catch (AuthenticationException e) {
            log.error("账号或密码错误!", e);
            return "账号或密码错误!";
        } catch (AuthorizationException e) {
            log.error("没有权限!", e);
            return "没有权限";
        }
        return "login success";
    }

    @RequiresRoles("admin")
    @GetMapping("/admin")
    public String admin() {
        return "admin success!";
    }

    @RequiresPermissions("query")
    @GetMapping("/index")
    public String index() {
        return "index success!";
    }

    @RequiresPermissions("add")
    @GetMapping("/add")
    public String add() {
        return "add success!";
    }
}

2.6🔑业务实现代码

import com.example.demo.bean.User;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: lidh
 * @Date: 2023/04/17/22:09
 * @Description:
 */
public interface LoginService {
    public User getUserByName(String getMapByName);
}
import com.example.demo.bean.Permissions;
import com.example.demo.bean.Role;
import com.example.demo.bean.User;
import com.example.demo.service.LoginService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: lidh
 * @Date: 2023/04/17/22:09
 * @Description:
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Override
    public User getUserByName(String getMapByName) {
        return getMapByName(getMapByName);
    }

    /**
     * 模拟数据库查询
     *
     * @param userName 用户名
     * @return User
     */
    private User getMapByName(String userName) {
        Permissions permissions1 = new Permissions("1", "query");
        Permissions permissions2 = new Permissions("2", "add");
        Set<Permissions> permissionsSet = new HashSet<>();
        permissionsSet.add(permissions1);
        permissionsSet.add(permissions2);
        Role role = new Role("1", "admin", permissionsSet);
        Set<Role> roleSet = new HashSet<>();
        roleSet.add(role);
        User user = new User("1", "wsl", "123456", roleSet);
        Map<String, User> map = new HashMap<>();
        map.put(user.getUserName(), user);

        Set<Permissions> permissionsSet1 = new HashSet<>();
        permissionsSet1.add(permissions1);
        Role role1 = new Role("2", "user", permissionsSet1);
        Set<Role> roleSet1 = new HashSet<>();
        roleSet1.add(role1);
        User user1 = new User("2", "zhangsan", "123456", roleSet1);
        map.put(user1.getUserName(), user1);
        return map.get(userName);
    }
}

三.🖍️测试:

🔎1.测试登录:浏览器输入:http://localhost:8080/login?userName=zhangsan&password=123456

完成登录。

🔎2.测试进入首页:http://localhost:8080/index

🔎3.测试换账号登录:http://localhost:8080/loginuserName=zhangsan&password=123456

四、📚参考文献

📃Apache Shiro官方文档:Apache Shiro Documentation | Apache Shiro

📃SpringBoot官方文档:Spring Boot Reference Documentation

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐