百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

什么是Apache Shiro?SpringBoot中如何整合Apache Shiro?

wxin55 2025-05-03 17:11 2 浏览 0 评论

Apache Shiro是一个功能强大且易于使用的Java安全框架,主要用于构建安全的企业应用程序,例如在应用中处理身份验证(Authentication)、授权(Authorization)、加密(Cryptography)和会话管理(Session Management)功能。其设置目标就是通过简单的灵活的操作来保证应用的安全性,下面我们就来看看在SpringBoot中如何整合Apache Shiro实现安全管理控制。

引入依赖

在pom.xml中引入Apache Shiro和Spring Boot Starter的依赖配置,如下所示。

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring-boot-starter</artifactId>
    <version>1.8.0</version>
</dependency>

配置 Shiro

接下来,需要定义Shiro相关的配置类,用来对相关的过滤器、Shiro的安全配置进行配置,如下所示。

import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.spring.web.config.AbstractShiroWebFilterConfiguration;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ShiroConfig {

    // 配置 SecurityManager
    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(customRealm()); // 设置自定义的Realm
        return securityManager;
    }

    // 配置 Shiro 的过滤器
    @Bean
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        shiroFilter.setSecurityManager(securityManager);

        // 配置拦截规则
        Map<String, String> filterChainDefinitionMap = new HashMap<>();
        filterChainDefinitionMap.put("/login", "anon");  // 不需要认证
        filterChainDefinitionMap.put("/logout", "logout"); // 退出
        filterChainDefinitionMap.put("/**", "authc");     // 其他请求需要认证

        shiroFilter.setFilterChainDefinitionMap(filterChainDefinitionMap);
        shiroFilter.setLoginUrl("/login"); // 设置登录 URL
        return shiroFilter;
    }

    // 配置自定义的Realm
    @Bean
    public CustomRealm customRealm() {
        return new CustomRealm();
    }
}

自定义 Realm

Realm作为Shiro中用来处理用户身份验证和授权的核心部分,在实际开发中通常需要我们自定义一个 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.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class CustomRealm extends AuthorizingRealm {

    // 进行身份验证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;

        // 假设用户名为 admin,密码为 123456
        if (!"admin".equals(userToken.getUsername())) {
            throw new AuthenticationException("用户不存在");
        }

        // 返回认证信息(包括用户名和加密后的密码)
        return new SimpleAuthenticationInfo("admin", "123456", getName());
    }

    // 进行授权
    @Override
    protected void doGetAuthorizationInfo(PrincipalCollection principals) {
        // 可根据具体的角色或权限做授权处理
    }

    // 设置密码匹配规则,比如可以设置加密算法
    @Override
    public void setCredentialsMatcher(HashedCredentialsMatcher credentialsMatcher) {
        super.setCredentialsMatcher(credentialsMatcher);
    }
}

配置密码加密和匹配

一般进行安全授权以及身份证认证的时候,都会对用户密码进行加密存储,而在Shiro中也提供了加密和匹配机制,如下所示。

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.context.annotation.Bean;

@Configuration
public class ShiroHashedCredentialsConfig {

    // 配置密码匹配器
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("SHA-256"); // 设置加密算法
        matcher.setHashIterations(1024); // 设置加密次数
        return matcher;
    }

    // 在 Realm 中使用密码匹配器
    @Bean
    public CustomRealm customRealm() {
        CustomRealm realm = new CustomRealm();
        realm.setCredentialsMatcher(hashedCredentialsMatcher());
        return realm;
    }

    // 加密方法示例
    public String encryptPassword(String password) {
        String salt = "12345";  // 盐值可以更复杂一些
        return new SimpleHash("SHA-256", password, salt, 1024).toHex();
    }
}

控制器中使用Shiro

最后,在 Spring Boot 控制器中,可以使用 Shiro 的 SecurityUtils 来进行用户登录、退出操作。

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {

    @PostMapping("/login")
    public String login(String username, String password) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token); // 执行登录
            return "登录成功";
        } catch (Exception e) {
            return "登录失败: " + e.getMessage();
        }
    }

    @RequestMapping("/logout")
    public String logout() {
        SecurityUtils.getSubject().logout(); // 执行退出
        return "退出成功";
    }
}

总结

在上面的例子中我们演示了在Spring Boot中整合 Apache Shiro的过程。通过这些步骤,我们就可以实现在Spring Boot应用中基于Shiro的安全控制机制,当然我们也可以对其进行扩展完善,来满足我们的更多的需求。

相关推荐

Shiro学习系列教程三:集成web(web集成环境)

相关推荐:《Shiro学习系列教程一:Shiro之helloworld》《Shiro学习系列教程三:集成web》《Shiro学习系列教程四:集成web(二)》《Shiro学习系列教程五:自定义Real...

写了这么多年代码,这样的登录方式还是头一回见

SpringSecurity系列还没搞完,最近还在研究。有的时候我不禁想,如果从SpringSecurity诞生的第一天开始,我们就一直在追踪它,那么今天再去看它的源码一定很简单,因为我们了...

Shiro框架:认证和授权原理(shiro框架授权的四种方式)

优质文章,及时送达前言Shiro作为解决权限问题的常用框架,常用于解决认证、授权、加密、会话管理等场景。本文将对Shiro的认证和授权原理进行介绍:Shiro可以做什么?、Shiro是由什么组成的?举...

Spring Boot 整合 Shiro-登录认证和权限管理

这篇文章我们来学习如何使用SpringBoot集成ApacheShiro。安全应该是互联网公司的一道生命线,几乎任何的公司都会涉及到这方面的需求。在Java领域一般有SpringS...

Apache Shiro权限管理解析二Apache Shiro核心组件

ApacheShiro核心组件Subject(用户主体)Subject是Shiro中的核心概念之一,表示当前用户(可以是登录的用户或匿名用户)。它是与用户交互的主要接口,提供了对用户身份验证...

详细介绍一下Apache Shiro的实现原理?

ApacheShiro是一个强大、灵活的Java安全框架,设计目标是简化复杂的安全需求,提供灵活的API,使开发者能方便地将安全功能集成到任何应用中。主要作用是用于管理身份验证、授权、会话管理和加...

什么是Apache Shiro?SpringBoot中如何整合Apache Shiro?

ApacheShiro是一个功能强大且易于使用的Java安全框架,主要用于构建安全的企业应用程序,例如在应用中处理身份验证(Authentication)、授权(Authorization)、加密(...

Apache Shiro权限管理解析三Apache Shiro应用

Shiro的优势与适用场景优势简单易用:API设计直观,适合中小型项目快速实现权限管理。灵活性高:支持多种数据源(数据库、LDAP等),并允许开发者自定义Realm。跨平台支持:不仅限于We...

那些通用清除软件不曾注意的秘密(清理不需要的应用)

系统清理就像卫生检查前的大扫除,即使你使出吃奶的劲儿把一切可能的地方都打扫过,还会留下边边角角的遗漏。随着大家电脑安全意识的提高,越来越多的朋友开始关注自己的电脑安全,也知道安装360系列软件来"武装...

JWT在跨域认证中的奇妙应用(jq解决跨域)

JWT在跨域认证中的奇妙应用什么是JWT?让我们先来聊聊JWT(JSONWebToken)。它是一种轻量级的认证机制,就像一张电子车票,能让用户在不同的站点间通行无阻。JWT由三部分组成:头部(H...

开启无痕浏览模式真能保护个人隐私吗?

在访问网站页面时,你是否有过这样的疑虑,自己访问的会不会是山寨网站?用公用电脑上网,个人信息会被别人看到吗?这时,有人会说,使用浏览器的“无痕浏览”模式不就行了,可以在操作中不留下“蛛丝马迹”,但,真...

辅助上网为啥会被抛弃 曲奇(Cookie)虽甜但有毒

近期有个小新闻,大概很多小伙伴都没有注意到,那就是谷歌Chrome浏览器要弃用Cookie了!说到Cookie功能,很多小伙伴大概觉得不怎么熟悉,有可能还不如前一段时间被弃用的Flash“出名”,但它...

cookie、session和token(cookie,session和token的区别)

Cookie的概念最早是在1994年由NetscapeCommunications的程序员LouMontulli发明的,目的是为了解决当时早期互联网的一个关键问题:HTTP无状态协...

小白都能看懂的session与cookie的区别理解

cookie/session都是跟踪识别浏览器用户身份的一个东西。cookie的理解:我们要知道,服务器和客户端之间进行数据传输,需要使用到一个超文本传输协议(http协议),而http协议本身是个...

面试:网易一面:支撑10万QPS的电商购物车系统如何架构设计呢?

1.需求分析:10万QPS的购物车系统需要满足哪些需求?回答:10万QPS的购物车系统需要满足以下核心需求和挑战:核心功能:添加、删除、修改购物车商品实时查看购物车列表支持高并发读写(10万QPS)...

取消回复欢迎 发表评论: