权限Shiro框架自定义Realm实现案例

mac2024-08-21  64

1、创建maven项目,添加依赖
<dependencies> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.4.0</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.5</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.5</version> </dependency> </dependencies>
2、创建自定义类,继承AuthorizingRealm

有两个方法需要重写,第一个方法用来做授权(给用户授权一些角色信息 ,权限信息),第二个方法用来做认证(登录使用)

2、实现认证方法
//模拟数据 Map<String,Object> map=new HashMap<String,Object>(); { map.put("zhangsan","123456"); super.setName("reol"); } /** * 用来做认证 * @param authenticationToken * @return * @throws AuthenticationException */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { //1、从主题传过来的认证信息中获取用户名 String username= (String) authenticationToken.getPrincipal(); //2通过用户名到数据库获取认证信息 String password=this.getPassWordByName(username); if(password==null){ //用户名不存在 return null; } //创建SimpleAuthenticationInfo SimpleAuthenticationInfo authenticationInfo=new SimpleAuthenticationInfo(username,password,"reol"); return authenticationInfo; } /** 用来模拟从数据库里查询数据 */ private String getPassWordByName(String username) { return (String) map.get(username); }
3、创建测试类测试登录功能
public class MyRealmTest { @Test public void Authentication(){ //创建自定义Realm对象 MyRealm jdbcRealm=new MyRealm(); //1、构建SecurityManager环境 DefaultSecurityManager defaultSecurityManager=new DefaultSecurityManager(); defaultSecurityManager.setRealm(jdbcRealm); //2、主题提交认证请求 SecurityUtils.setSecurityManager(defaultSecurityManager); Subject subject=SecurityUtils.getSubject(); //3、提交认证 UsernamePasswordToken Token=new UsernamePasswordToken("zhangsan","123456"); //登录认证 subject.login(Token); System.out.println(subject.isAuthenticated()); }

执行测试类即可,当控制台输出true时,表示已经认证成功。 当用户名输入错位时,控制台会出现这个错误 当秘密错误时,控制台会报这个错误

4、实现授权方法
/** * 用来做授权 * @param principalCollection * @return */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { //1、从主题传过来的认证信息中获取用户名 String username= (String) principalCollection.getPrimaryPrincipal(); //获取用户的角色信息 Set<String> roles=getRolesName(username); SimpleAuthorizationInfo simpleAuthenticationInfo=new SimpleAuthorizationInfo(); simpleAuthenticationInfo.setRoles(roles); return simpleAuthenticationInfo; } /** * 因为没有连接数据库,所以这里直接模拟一下数据 * @return */ public Set<String> getRolesName(String username) { Set<String> set=new HashSet<>(); set.add("admin"); set.add("user"); return set; }
5、验证用户角色信息

只需要在刚才的测试类中添加以下代码即可

subject.checkRoles("admin");

当输入不存在的角色名称时会报以下错误

最新回复(0)