JFinal 整合 Shiro 补充Realm类和数据库

JFinal 整合 Shiro原文:

http://my.oschina.net/smile622/blog/135098

 

在此基础上 补充数据库和MyShiroRealm.java

users表

SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `users`
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) DEFAULT NULL,
  `password` varchar(50) DEFAULT NULL,
  `mail` varchar(100) DEFAULT NULL,
  `roleid` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `RoleId` (`roleid`),
  CONSTRAINT `users_ibfk_1` FOREIGN KEY (`roleid`) REFERENCES `roles` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=43 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of users
-- ----------------------------
INSERT INTO `users` VALUES ('1', '1', '1', '[email protected]', '1');
INSERT INTO `users` VALUES ('2', 'admin', 'admin', '[email protected]', '2');

roles表

SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `roles`
-- ----------------------------
DROP TABLE IF EXISTS `roles`;
CREATE TABLE `roles` (
  `id` int(11) NOT NULL,
  `rolename` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of roles
-- ----------------------------
INSERT INTO `roles` VALUES ('1', 'user');
INSERT INTO `roles` VALUES ('2', 'sysadmin');

MyShiroRealm.java

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;

import xxx.model.Roles;
import xxx.model.Users;

/**
 * 自实现用户与权限查询. 演示关系,密码用明文存储,因此使用默认 的SimpleCredentialsMatcher.
 */
public class MyShiroRealm extends AuthorizingRealm {

	/**
	 * 认证回调函数, 登录时调用.
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;

		String password = String.valueOf(token.getPassword());
		// 调用操作数据库的方法查询user信息
		Users user = Users.dao.findFirst(
				"select * from users where username = ?", token.getUsername());
		if (user != null) {
			if (password.equals(user.getStr("password"))) {
				Session session = SecurityUtils.getSubject().getSession();
				session.setAttribute("username", user.getStr("username"));
				return new SimpleAuthenticationInfo(user.getInt("id"),
						user.getStr("password"), getName());
			} else {
				return null;
			}
		} else {
			return null;
		}
	}

	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		int userId = (int) principals.fromRealm(getName()).iterator().next();
		Users user = Users.dao.findById(userId);
		if (user != null) {
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			Roles role = Roles.dao.findById(user.getInt("roleid"));
			info.addRole(role.getStr("rolename"));
			// info.addStringPermissions( role.getPermissions()
			// );//如果你添加了对权限的表,打开此注释,添加角色具有的权限

			return info;
		} else {
			return null;
		}
	}

}

 

FreeMarker添加Shiro标签(需要加入shiro-freemarker-tags-0.1-SNAPSHOT.jar)

FreeMarkerRender.getConfiguration().setSharedVariable("shiro", new ShiroTags()); // FreeMarker中使用shiro标签

到这一步基本的权限就够了

附带Shiro.ini

[main]
shiro.loginUrl = /login

#realm
myRealm = xxx.manage.shiro.ShiroDbRealm
securityManager.realm = $myRealm

#cache
shiroCacheManager = org.apache.shiro.cache.ehcache.EhCacheManager
shiroCacheManager.cacheManagerConfigFile = classpath:ehcache-shiro.xml
securityManager.cacheManager = $shiroCacheManager

#session
sessionDAO = org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO
sessionManager = org.apache.shiro.web.session.mgt.DefaultWebSessionManager
sessionDAO.activeSessionsCacheName = shiro-activeSessionCache
sessionManager.sessionDAO = $sessionDAO
securityManager.sessionManager = $sessionManager
securityManager.sessionManager.globalSessionTimeout = 360000

#这里的规则,web.xml中的配置的ShiroFilter会使用到。
[urls]
/manage/** = authc, roles[user]
/** = anon

密码加密等其他功能请另查阅资料,如需更多复杂应用请查阅http://www.oschina.net/question/925382_114550

 

你可能感兴趣的:(sql,shiro,jFinal,DbRealm)