要在项目中使用Shiro,搭建Shiro环境通常需要进行以下步骤。
1. 添加Shiro依赖
在项目的 pom.xml 文件中添加Shiro的依赖:
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.7.1</version>
</dependency>
2. 配置Shiro
创建一个Shiro配置类,配置Shiro的各种组件,如SecurityManager和Realm等。
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.text.TextConfigurationRealm;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
public class ShiroConfig {
public SecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(textConfigurationRealm());
return securityManager;
}
public Realm textConfigurationRealm() {
TextConfigurationRealm realm = new TextConfigurationRealm();
realm.setUserDefinitions("user1=password1,role1\nuser2=password2,role2");
return realm;
}
}
3. 编写登录验证逻辑
编写一个简单的登录验证逻辑,包括身份验证和授权。
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
public class LoginService {
public void login(String username, String password) {
Subject currentUser = SecurityUtils.getSubject();
if (!currentUser.isAuthenticated()) {
AuthenticationToken token = new UsernamePasswordToken(username, password);
try {
currentUser.login(token);
System.out.println("登录成功!");
} catch (AuthenticationException e) {
System.out.println("登录失败:" + e.getMessage());
}
}
}
}
4. 测试代码
编写一个简单的测试代码来测试Shiro的登录功能。
public class Main {
public static void main(String[] args) {
ShiroConfig shiroConfig = new ShiroConfig();
SecurityManager securityManager = shiroConfig.securityManager();
SecurityUtils.setSecurityManager(securityManager);
LoginService loginService = new LoginService();
loginService.login("user1", "password1");
}
}
以上是一个简单的Shiro环境搭建的步骤。