shiro学习(2)-自定义Realm

通过shiro学习(1)我们发现仅仅将数据源信息定义在ini文件中与我们实际开发环境有很大不兼容,所以我们希望能够自定义Realm。

自定义Realm的实现

创建自定义ShiroRealmsOne类

创建一个java文件继承AuthorizingRealm类,重写两个抽象方法

public class ShiroRealmsOne extends AuthorizingRealm{
	/**
	 * 认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String username =(String)token.getPrincipal();
		if(!"admin".equals(username)){
			return null;
		}
		String password = "123456";
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username,password,this.getName());
		return info;
	}

	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO 自动生成的方法存根
		return null;
	}

	

}
方法名 说明
doGetAuthenticationInfo 完成账号认证的方法
doGetAuthorizationInfo 完成账号授权的方法

 配置shiro-realm.ini文件

[main]
shiroUserRealm=com.sumeng.shiro.ShiroRealmsOne
securityManager.realms=$shiroUserRealm

 测试

@Test
	public void demoTwo(){
		// 装入 INI 配置
		Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-realms.ini");
		//创建SecurityManager对象
		SecurityManager instance = factory.getInstance();
		//使SecurityManager可以访问
		SecurityUtils.setSecurityManager(instance);
		//接受提交的用户名和密码: 
		UsernamePasswordToken tooken = new UsernamePasswordToken("admin","123456");
		//获取当前主体
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(tooken);
		} catch (AuthenticationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("是否认证成功:" + subject.isAuthenticated());
	}

用户名和密码正确

用户名错误

密码错误

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章