在当今的互联网时代,安全认证和权限管理是保障系统安全的关键。Shiro 是一个强大而灵活的开源安全框架,可以帮助开发者轻松实现安全认证和权限管理。本文将从零开始,带你轻松掌握 Shiro 框架的集成,包括安全认证和权限管理的实战攻略。
一、Shiro 简介
Shiro 是一个Java安全框架,它为应用提供了身份验证、授权、会话管理和加密等功能。Shiro 的核心组件包括:
- Subject:当前执行用户
- SecurityManager:安全管理器,负责管理内部组件
- Realm:领域,负责认证和授权
- Session:会话,用于存储用户状态信息
- Cache:缓存,用于提高性能
二、Shiro 集成步骤
下面我们以一个简单的 Spring Boot 项目为例,演示如何集成 Shiro。
1. 添加依赖
在项目的 pom.xml 文件中添加 Shiro 和 Spring Boot 的依赖:
<dependencies>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-starter</artifactId>
<version>1.8.0</version>
</dependency>
<!-- Spring Boot 依赖 ... -->
</dependencies>
2. 配置 Shiro
在 application.properties 或 application.yml 文件中配置 Shiro:
shiro.config.location=classpath:shiro.ini
3. 创建 Shiro 配置文件
创建 shiro.ini 文件,配置 Realm、过滤器等:
[main]
# Realm
authcRealm=myAuthcRealm
# 过滤器
urls=/** = authc
# 会话管理
session.cookie.name=shiroSessionId
session.cookie.maxAge=-1
session.timeout=1800
sessionValidationInterval=3000
sessionStorageMode=none
# 缓存管理
cacheManager=org.apache.shiro.cache.ehcache.EhCacheManager
cacheManager.cacheNames=shiroCache
4. 创建 Realm
创建 MyAuthcRealm 类,继承自 AuthorizingRealm:
public class MyAuthcRealm extends AuthorizingRealm {
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// 根据用户名获取用户信息
String username = (String) token.getPrincipal();
// 根据用户名获取密码
String password = getPasswordByUsername(username);
if (password == null) {
throw new UnknownAccountException("用户不存在");
}
return new SimpleAuthenticationInfo(username, password, getName());
}
private String getPasswordByUsername(String username) {
// 根据用户名获取密码,此处为示例,实际项目中应从数据库或其他存储中获取
return "123456";
}
}
5. 创建 Shiro Filter
创建 ShiroFilter 类,继承自 FormAuthenticationFilter:
public class ShiroFilter extends FormAuthenticationFilter {
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
// 根据需要判断是否允许访问
return super.isAccessAllowed(request, response, mappedValue);
}
}
6. 配置 Spring Boot
在 application.properties 或 application.yml 文件中配置 Shiro Filter:
server.servlet.filter-name.shiroFilter
server.servlet.filter-url-pattern=/**
server.servlet.filter-registration-order=2
三、安全认证与权限管理
1. 安全认证
在控制器或服务中,使用 @RequiresAuthentication 注解来标识需要认证的方法:
@RestController
@RequestMapping("/user")
public class UserController {
@RequiresAuthentication
@GetMapping("/info")
public String getInfo() {
return "当前用户:" + SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
}
2. 权限管理
在控制器或服务中,使用 @RequiresPermissions 注解来标识需要特定权限的方法:
@RestController
@RequestMapping("/admin")
public class AdminController {
@RequiresPermissions("admin:edit")
@GetMapping("/edit")
public String edit() {
return "编辑权限";
}
}
四、总结
通过本文的介绍,相信你已经对 Shiro 框架有了初步的了解。Shiro 框架可以帮助开发者轻松实现安全认证和权限管理。在实际项目中,你可以根据需求进行扩展和定制,以满足各种安全需求。希望本文对你有所帮助!
