本文介绍在自定义Realm中实现从数据库中动态获取用户信息、角色信息和权限信息的详细步骤。
1. 创建数据库表
创建数据库表用于存储用户信息、角色信息和权限信息。
2. 自定义Realm
创建一个自定义的Realm,继承 AuthorizingRealm
类并实现从数据库中获取用户信息、角色信息和权限信息的逻辑。
import org.apache.shiro.authc.*;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
public class CustomRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String username = (String) principals.getPrimaryPrincipal();
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
// 从数据库中获取用户角色信息和权限信息
User user = userService.getUserByUsername(username);
for (Role role : user.getRoles()) {
authorizationInfo.addRole(role.getName());
for (Permission permission : role.getPermissions()) {
authorizationInfo.addStringPermission(permission.getName());
}
}
return authorizationInfo;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
String username = usernamePasswordToken.getUsername();
String password = new String(usernamePasswordToken.getPassword());
// 从数据库中查询用户信息
User user = userService.getUserByUsername(username);
if (user == null) {
throw new UnknownAccountException("用户名不存在");
}
// 校验密码
if (!password.equals(user.getPassword())) {
throw new IncorrectCredentialsException("密码错误");
}
return new SimpleAuthenticationInfo(username, password, getName());
}
}
3. UserService
创建一个UserService类,用于从数据库中获取用户信息。
import org.springframework.stereotype.Service;
@Service
public class UserService {
public User getUserByUsername(String username) {
// 实现从数据库中查询用户信息的逻辑
}
}
4. 配置Shiro
在Shiro配置类中注入自定义Realm和UserService。
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ShiroConfig {
@Bean
public SecurityManager securityManager(Realm customRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(customRealm);
return securityManager;
}
@Bean
public Realm customRealm() {
return new CustomRealm();
}
@Bean
public UserService userService() {
return new UserService();
}
}
通过以上代码,实现了在自定义Realm
中从数据库动态获取信息实现授权逻辑和认证逻辑的功能。