Shiro 是一个开源的安全框架,用于实现身份验证、授权、会话管理和加密等安全功能。在Spring Boot项目中集成Shiro,可以让我们快速实现安全认证,保护我们的应用不受未授权访问。本文将详细讲解如何在Spring Boot项目中集成Shiro,让新手也能轻松上手。
1. 准备工作
在开始集成Shiro之前,我们需要准备以下内容:
- Spring Boot项目
- Shiro依赖
1.1 添加Shiro依赖
在Spring Boot项目的pom.xml文件中添加以下依赖:
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-starter</artifactId>
<version>1.8.0</version>
</dependency>
这里使用的是Shiro的Spring Boot启动器,它会自动配置Shiro,简化集成过程。
2. 配置Shiro
在Spring Boot项目的application.properties或application.yml文件中,添加以下配置:
shiro.cache.type=eclipse
shiro.session.timeout=1800
这里配置了Shiro的缓存类型为Eclipse,会话超时时间为1800秒。
3. 编写Shiro配置类
创建一个Shiro配置类,用于配置Shiro的权限管理、认证管理等。
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ShiroConfig {
@Bean
public SecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(realm());
securityManager.setSessionManager(sessionManager());
return securityManager;
}
@Bean
public IniRealm realm() {
IniRealm realm = new IniRealm();
realm.setCachingEnabled(true);
realm.setCacheManager(cacheManager());
realm.setAuthenticationInfoCacheName("AuthenticationCache");
realm.setAuthorizationInfoCacheName("AuthorizationCache");
realm.setUsersFileName("classpath:shiro.ini");
return realm;
}
@Bean
public CacheManager cacheManager() {
return new CacheManager() {
@Override
public Object getCache(String name) {
return null;
}
@Override
public void putCache(String name, Object value) {
}
@Override
public void removeCache(String name) {
}
@Override
public void clearCache(String name) {
}
@Override
public void destroy() {
}
};
}
@Bean
public SessionManager sessionManager() {
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
sessionManager.setGlobalSessionTimeout(1800 * 1000);
return sessionManager;
}
@Bean
public AuthorizationInfo authorizationInfo() {
return new SimpleAuthorizationInfo();
}
@Bean
public AuthenticationInfo authenticationInfo() {
return new AuthenticationInfo("username", "password", authorizationInfo());
}
}
这里配置了Shiro的SecurityManager、Realm、SessionManager等。在realm()方法中,我们加载了Shiro的配置文件shiro.ini,其中包含了用户名、密码和权限信息。
4. 编写登录控制器
创建一个登录控制器,用于处理登录请求。
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping("/login")
public class LoginController {
@GetMapping
public String login() {
return "login";
}
@PostMapping
public String doLogin(@RequestParam("username") String username,
@RequestParam("password") String password) {
try {
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
subject.login(token);
return "redirect:/";
} catch (AuthenticationException e) {
return "login";
}
}
}
这里使用了Shiro的Subject对象进行登录验证。如果登录成功,则重定向到首页;如果登录失败,则返回登录页面。
5. 配置拦截器
创建一个拦截器,用于拦截未登录用户的请求。
import org.apache.shiro.web.filter.authc.AuthorizationFilter;
import org.springframework.stereotype.Component;
@Component
public class ShiroInterceptor extends AuthorizationFilter {
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
Subject subject = SecurityUtils.getSubject();
return subject.isAuthenticated();
}
}
这里继承自Shiro的AuthorizationFilter,重写了isAccessAllowed方法,用于判断用户是否已登录。
在Spring Boot项目中,我们还需要在WebMvcConfigurer接口中注册拦截器:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private ShiroInterceptor shiroInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(shiroInterceptor).addPathPatterns("/**").excludePathPatterns("/login");
}
}
这里注册了ShiroInterceptor拦截器,拦截所有请求,除了登录请求。
6. 总结
通过以上步骤,我们成功在Spring Boot项目中集成了Shiro,并实现了安全认证。本文详细讲解了Shiro的集成过程,包括准备工作、配置Shiro、编写Shiro配置类、编写登录控制器和配置拦截器。希望本文能帮助新手快速上手Shiro,实现Spring Boot项目的安全认证。