Shiro(九)SpringBoot集成

686 阅读3分钟

介绍

提供在实际项目中我们通过Spring或者SpringBoot来集成Shiro来进行权限的校验和用户的认证,下面是SpringBoot集成Shiro的步骤:

集成

添加依赖

  1. 添加相关依赖:在pom.xml文件中添加以下依赖:前提是已经新建成功SpringBoot项目
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring</artifactId>
    <version>1.4.1</version>
</dependency>

配置

  1. 配置Shiro:在application.yml文件中添加Shiro的配置,配置Shiro的登录Url、登录成功地址,未授权需要跳转的页面 例如:
shiro:
  login-url: /login
  success-url: /index
  unauthorized-url: /403

  # shiro filter chain definitions
  filter-chain-definition-map:
    /logout: logout
    /**: user

设置配置类

  1. 创建Shiro的配置类:创建一个Shiro配置类,例如:
@Configuration
public class ShiroConfig {
    
    // 配置SecurityManager
    @Bean
    public DefaultWebSecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(myRealm());
        return securityManager;
    }
    
    // 自定义Reaml
    @Bean
    public MyRealm myRealm() {
        MyRealm realm = new MyRealm();
        return realm;
    }
    
    // 配置 Shiro的拦截过滤器
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        filterChainDefinitionMap.put("/login", "anon");
        filterChainDefinitionMap.put("/logout", "logout");
        filterChainDefinitionMap.put("/static/**", "anon");
        filterChainDefinitionMap.put("/**", "authc");

        shiroFilterFactoryBean.setLoginUrl("/login");
        shiroFilterFactoryBean.setSuccessUrl("/index");
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        
        return shiroFilterFactoryBean;
    }
}

自定义 Realm

  1. 创建自定义Realm:创建一个自定义的Realm类,例如:
public class MyRealm extends AuthorizingRealm {

    private static final Logger logger = LoggerFactory.getLogger(MyRealm.class);

    @Autowired
    private UserService userService;

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        User user = (User) principals.getPrimaryPrincipal();
        authorizationInfo.setRoles(userService.getUserRoles(user.getId()));
        authorizationInfo.setStringPermissions(userService.getUserPermissions(user.getId()));
        return authorizationInfo;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();
        String password = usernamePasswordToken.getPassword();

        User user = userService.getUserByUsernameAndPassword(username, password);

        if (user == null) {
            throw new UnknownAccountException("账号或密码不正确");
        }

        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), getName());
        return authenticationInfo;
    }
}

这样,SpringBoot与Shiro的集成就完成了。可以在Controller中使用Shiro的注解来进行权限控制。例如:

@RequestMapping("/user")
@RequiresPermissions("user:view")
public String index(Model model) {
    List<User> userList = userService.getAllUsers();
    model.addAttribute("userList", userList);
    return "user/index";
}

以上便是SpringBoot集成Shiro的全过程。

注意事项

在集成SpringBoot与Shiro时,需要注意以下几点:

  1. 版本兼容性:需要选择相应版本的Shiro与SpringBoot进行集成。建议选择相对稳定的版本,并对所有相关依赖进行版本统一管理。

  2. 配置文件设置:需要在配置文件中设置Shiro的相关配置,例如登录界面、成功跳转界面、未授权界面等,也可以通过配置进行配置或者 shiro提供的ini配置文件。

  3. 自定义Realm:需要自定义Realm,实现Shiro的认证和授权功能。在认证过程中,需要对账号和密码进行验证;在授权过程中,需要从数据库或其他数据源中获取用户的角色和权限信息,使用数据库注意数据的链接问题。

  4. 注解使用:需要在Controller层使用Shiro的注解进行权限控制,例如@RequiresPermissions。但是要注意,在使用注解过程中,需要保证Realm中能够正确获取用户的角色和权限信息,在注解的使用过程中需要指定相应的角色和权限。

  5. Realm注册:需要将自定义的Realm注册到Shiro安全管理器中。在注册过程中,需要将Shiro的配置文件中的相关参数传递给安全管理器,例如过滤器链定义、自定义的Realm等。

总体来说,集成SpringBoot与Shiro并没有什么特别难理解的地方法,理解Shiro的基本概念和工作原理,同时需要注意版本兼容性和配置文件设置,就可以轻松解决Shiro认证授权控制的理解和使用。