在当今的Web开发中,权限管理是一个至关重要的环节。Shiro 是一个强大的Java安全框架,它可以帮助我们轻松实现身份验证、授权以及会话管理等安全功能。而Spring Boot则以其简洁的配置和自动化的特性,成为Java开发者的热门选择。本文将带你轻松上手Boot集成Shiro,实现权限管理。
一、Shiro简介
Shiro是一个开源的安全框架,它提供了认证(Authentication)、授权(Authorization)、会话管理(Session Management)和加密(Cryptography)等功能。Shiro的核心组件包括:
- Subject:当前登录的用户。
- SecurityManager:Shiro的核心,负责管理内部组件。
- Realm:用于从数据库或其他数据源获取认证信息和授权信息。
- SessionManager:用于管理会话。
二、Boot集成Shiro
1. 添加依赖
首先,在你的Spring Boot项目中添加Shiro的依赖。以下是Maven的依赖配置:
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-web-starter</artifactId>
<version>1.7.0</version>
</dependency>
2. 配置Shiro
在application.properties或application.yml中配置Shiro:
shiro.config.location=classpath:shiro.ini
3. 创建Shiro配置文件
创建一个名为shiro.ini的文件,配置Shiro的各个组件:
[main]
# 定义SecurityManager
securityManager.realms=myRealm
# 定义SessionManager
sessionManager.sessionValidationInterval=1800
sessionManager.globalSessionTimeout=3600
sessionManager.sessionValidationSchedulerEnabled=true
# 定义缓存管理器
cacheManager.cacheManager=org.apache.shiro.cache.ehcache.EhCacheCacheManager
cacheManager.cacheManager.cacheManagerConfig=org.apache.shiro.cache.ehcache.EhcacheManager
# 定义Cookie模板
cookie.name=shiroCookie
cookie.maxAge=-1
cookie.path=/
cookie.httpOnly=true
cookie.secure=false
cookie.domain=
cookie.comment=
cookie.version=0
4. 创建Realm
创建一个继承自AuthorizingRealm的类,用于获取认证和授权信息:
@Component
public class MyRealm extends AuthorizingRealm {
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// 从token中获取用户名和密码
String username = (String) token.getPrincipal();
String password = new String((char[]) token.getCredentials());
// 从数据库中获取用户信息
User user = userService.findUserByUsername(username);
// 判断用户是否存在
if (user == null) {
throw new UnknownAccountException("用户不存在");
}
// 判断密码是否正确
if (!password.equals(user.getPassword())) {
throw new IncorrectCredentialsException("密码错误");
}
// 返回认证信息
return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
// 从principals中获取用户信息
User user = (User) getAuthenticationInfo(principals).getPrincipal();
// 根据用户信息获取权限信息
List<String> permissions = userService.findPermissionsByUsername(user.getUsername());
// 返回授权信息
return new SimpleAuthorizationInfo(permissions);
}
}
5. 配置Spring Security
在SecurityConfig类中配置Spring Security,使其使用Shiro:
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyRealm myRealm;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(myRealm);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.ALWAYS)
.and()
.exceptionHandling()
.authenticationEntryPoint(new AuthenticationEntryPoint() {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write("未授权访问");
}
});
}
}
6. 使用Shiro注解
在Controller或Service层,使用Shiro提供的注解进行权限控制:
@RestController
@RequestMapping("/user")
public class UserController {
@PreAuthorize("hasAuthority('user:edit')")
@GetMapping("/edit/{id}")
public String edit(@PathVariable("id") Long id) {
return "编辑用户:" + id;
}
@PreAuthorize("hasAuthority('user:delete')")
@GetMapping("/delete/{id}")
public String delete(@PathVariable("id") Long id) {
return "删除用户:" + id;
}
}
三、总结
通过以上步骤,你已经成功将Shiro集成到Spring Boot项目中,并实现了基本的权限管理。当然,Shiro的功能远不止于此,你可以根据实际需求进行更深入的学习和探索。希望本文能帮助你轻松上手Boot集成Shiro,实现权限管理!