什么是Apache Shiro?SpringBoot中如何整合Apache Shiro?
Apache Shiro是一个功能强大且易于使用的Java安全框架,主要用于构建安全的企业应用程序,例如在应用中处理身份验证(Authentication)、授权(Authorization)、加密(Cryptography)和会话管理(Session Management)功能。其设置目标就是通过简单的灵活的操作来保证应用的安全性,下面我们就来看看在SpringBoot中如何整合Apache Shiro实现安全管理控制。
引入依赖
在pom.xml中引入Apache Shiro和Spring Boot Starter的依赖配置,如下所示。
org.apache.shiro
shiro-spring-boot-starter
1.8.0
配置 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 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的安全控制机制,当然我们也可以对其进行扩展完善,来满足我们的更多的需求。