自定义realm

一个用户可以有多个角色,一个角色可以有多个权限

一.所需表

1.角色表(t_role)

idint角色ID
roleNamevarchar角色名
2.用户表(t_user)
idint用户ID
userNamevarchar用户名
passwordvarchar密码
roleIdint外键关联角色表的id
3.权限表(t_permission)

idint权限ID
permissionNamevarchar权限名
roleIdint外键关联角色表的id
二.创建自定义realm类(继承AuthorizingRealm类)

public class MyRealm extends AuthorizingRealm{

	private UserDao userDao=new UserDao();
	private DbUtil dbUtil=new DbUtil();
	
	/**
	 * 为当前登录的用户授予角色和权限
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String userName=(String)principals.getPrimaryPrincipal();
/*
SimpleAuthorizationInfo 为AuthorizationInfo 的实现类,为授权信息类

调用authorizatioInfo的setRoles(Set<String> roleNames)设置角色

调用authorizatioInfo的setStringPermissions(Set<String> permissions)设置权限
*/
		SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
		Connection con=null;
		try{
			con=dbUtil.getCon();
			authorizationInfo.setRoles(userDao.getRoles(con,userName));
			authorizationInfo.setStringPermissions(userDao.getPermissions(con,userName));
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				dbUtil.closeCon(con);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return authorizationInfo;
	}

	/**
	 * 验证当前登录的用户
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String userName=(String)token.getPrincipal();
		Connection con=null;
		try{
			con=dbUtil.getCon();
			User user=userDao.getByUserName(con, userName);
			if(user!=null){
/**
SimpleAuthenticationInfo类为AuthenticationInfo类的实现类,为认证类

将从数据库获取的userName,password传进去会自动与token中的信息对比认证

*/

				AuthenticationInfo authcInfo=new SimpleAuthenticationInfo(user.getUserName(),user.getPassword(),"xx");
				return authcInfo;
			}else{
				return null;
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				dbUtil.closeCon(con);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

}

三.编写shiro.ini配置文件

[main]

#未通过认证的用户跳转到login
authc.loginUrl=/login

#为通过角色和权限的用户跳到unauthorized.jsp
roles.unauthorizedUrl=/unauthorized.jsp
perms.unauthorizedUrl=/unauthorized.jsp

#自定义realm所在类
myRealm=com.wm.realm.MyRealm

#将自定义的realm交给securityManager管理
securityManager.realms=$myRealm
[urls]

#各种请求所需的认证/角色/授权
/login=anon
/admin*=authc
/student=roles[teacher]
/teacher=perms["user:create"]


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值