shiro jdbcRealm

shiro成熟的例子还是很少,貌似springSide4 有个完整的例子。附件有简单数据库设计。

http://ynp.iteye.com/blog/1736824

package com.myShiro.test;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.subject.Subject;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
public class JdbcReamTest {

	public static void main(String[] args) {

		System.out.println("Hello shiro!");

		MysqlDataSource datasource = new MysqlDataSource();

		datasource.setUser("root");

		datasource.setPassword("root");

		datasource.setServerName("localhost");

		// datasource.setDriverClassName("com.mysql.jdbc.Driver");

		datasource.setUrl("jdbc:mysql://localhost:3306/test");

		// datasource.setMaxActive(10);

		org.apache.shiro.realm.jdbc.JdbcRealm jdbcRealm = new JdbcRealm();

		jdbcRealm.setDataSource(datasource);

		jdbcRealm.setPermissionsLookupEnabled(true);

		jdbcRealm
				.setAuthenticationQuery("SELECT PASSWORD FROM account WHERE name = ?");

		jdbcRealm
				.setUserRolesQuery("SELECT NAME FROM role WHERE id =(SELECT roleId FROM account_role WHERE userId = (SELECT id FROM account WHERE NAME = ?))");

		jdbcRealm
				.setPermissionsQuery("SELECT NAME FROM permission WHERE id in (SELECT permissionId FROM permission_role WHERE (SELECT id FROM role WHERE NAME = ?))");

		DefaultSecurityManager security = new DefaultSecurityManager(jdbcRealm);

		SecurityUtils.setSecurityManager(security);
		Subject currentUser = SecurityUtils.getSubject();
		if (!currentUser.isAuthenticated()) {

			UsernamePasswordToken token = new UsernamePasswordToken("ynp",
					"111111");

			token.setRememberMe(true);
			try {
				currentUser.login(token);

				System.out.println("login successfully");

			} catch (UnknownAccountException uae) {

				System.out.println("There is no user with username of "
						+ token.getPrincipal());

			} catch (IncorrectCredentialsException ice) {

				System.out.println("Password for account "
						+ token.getPrincipal() + " was incorrect!");

			} catch (LockedAccountException lae) {

				System.out.println("The account for username "
						+ token.getPrincipal() + " is locked.  " +

						"Please contact your administrator to unlock it.");

			}

			// ... catch more exceptions here (maybe custom ones specific to
			// your application?

			catch (AuthenticationException ae) {

				// unexpected condition? error?

			}

		}

		// say who they are:

		// print their identifying principal (in this case, a username):

		System.out.println("User [" + currentUser.getPrincipal()
				+ "] logged in successfully.");

		// test a role:

		if (currentUser.hasRole("admin")) {

			System.out.println("May the admin be with you!");

		} else {

			System.out.println("Hello, mere mortal.");

		}

		// test a typed permission (not instance-level)

		if (currentUser.isPermitted("write")) {
			System.out.println("You can write!.");
		} else {

			System.out.println("Sorry, lightsaber rings are for schwartz masters only.");
		}

		// a (very powerful) Instance Level permission:

		if (currentUser.isPermitted("winnebago:drive:eagle5")) {

			System.out
					.println("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  "
							+

							"Here are the keys - have fun!");

		} else {

			System.out
					.println("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");

		}

		// all done - log out!

		currentUser.logout();

	}

}
数据库脚本:
<pre class="sql" name="code">/*
SQLyog 企业版 - MySQL GUI v8.14 
MySQL - 5.0.68-enterprise-gpl-nt-log : Database - test
*********************************************************************
*/ 
/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`test` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `test`;

/*Table structure for table `account` */

DROP TABLE IF EXISTS `account`;

CREATE TABLE `account` (
  `ID` bigint(10) NOT NULL,
  `name` varchar(256) default NULL,
  `password` varchar(256) default NULL,
  PRIMARY KEY  (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Data for the table `account` */

insert  into `account`(`ID`,`name`,`password`) values (1,'ynp','111111');

/*Table structure for table `account_role` */

DROP TABLE IF EXISTS `account_role`;

CREATE TABLE `account_role` (
  `userId` bigint(10) default NULL,
  `roleId` bigint(10) default NULL,
  KEY `FK_Account_Role` (`roleId`),
  KEY `FK_Account_Role1` (`userId`),
  CONSTRAINT `FK_Account_Role` FOREIGN KEY (`roleId`) REFERENCES `role` (`ID`),
  CONSTRAINT `FK_Account_Role1` FOREIGN KEY (`userId`) REFERENCES `account` (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Data for the table `account_role` */

insert  into `account_role`(`userId`,`roleId`) values (1,1);

/*Table structure for table `permission` */

DROP TABLE IF EXISTS `permission`;

CREATE TABLE `permission` (
  `ID` bigint(10) NOT NULL,
  `name` varchar(256) default NULL,
  PRIMARY KEY  (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Data for the table `permission` */

insert  into `permission`(`ID`,`name`) values (1,'read'),(2,'write');

/*Table structure for table `permission_role` */

DROP TABLE IF EXISTS `permission_role`;

CREATE TABLE `permission_role` (
  `permissionId` bigint(10) default NULL,
  `roleId` bigint(10) default NULL,
  KEY `FK_PerMission_Role` (`roleId`),
  KEY `FK_PerMission_Role1` (`permissionId`),
  CONSTRAINT `FK_PerMission_Role` FOREIGN KEY (`roleId`) REFERENCES `role` (`ID`),
  CONSTRAINT `FK_PerMission_Role1` FOREIGN KEY (`permissionId`) REFERENCES `permission` (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Data for the table `permission_role` */

insert  into `permission_role`(`permissionId`,`roleId`) values (1,1),(2,1);

/*Table structure for table `role` */

DROP TABLE IF EXISTS `role`;

CREATE TABLE `role` (
  `ID` bigint(10) NOT NULL,
  `name` varchar(256) default NULL,
  PRIMARY KEY  (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Data for the table `role` */

insert  into `role`(`ID`,`name`) values (1,'admin');

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值