1.pom文件
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>0.2.23</version>
</dependency>
2.最基本的shiro
配置文件shiro
[users]
zhang=321
wang=123
代码
package com.knife.Shiro;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.apache.shiro.mgt.SecurityManager;
public class TestShiro {
public static void main(String args[]) {
// 1、获取SecurityManager工厂,此处使用Ini配置文件初始化SecurityManager
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro");
// 2、得到SecurityManager实例 并绑定给SecurityUtils
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
// 3、得到Subject及创建用户名/密码身份验证Token(即用户身份/凭证)
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("zhang", "321");
try {
// 4、登录,即身份验证
subject.login(token);
System.out.println("land success");
} catch (AuthenticationException e) {
// 5、身份验证失败
System.out.println("land faile,reason:"+e.getMessage());
}
System.out.println("land state:"+subject.isAuthenticated());
subject.logout();
System.out.println("land state:"+subject.isAuthenticated());
}
}
结果
land success
land state:true
land state:false
3.自定义realm
配置文件
myRealm=com.knife.Shiro.testRealm.MyRealm
securityManager.realms=$myRealm
代码
package com.knife.Shiro.testRealm;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.realm.Realm;
public class MyRealm implements Realm {
public String getName() {
// TODO Auto-generated method stub
return "myRealm";
}
public boolean supports(AuthenticationToken token) {
System.out.println("支持...");
// TODO Auto-generated method stub
return token instanceof UsernamePasswordToken;
}
public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("验证...");
// TODO Auto-generated method stub
String username = (String)token.getPrincipal(); //得到用户名
String password = new String((char[])token.getCredentials()); //得到密码
System.out.println("用户名:"+username+" 密码:"+password);
if(!"zhang".equals(username)) {
throw new UnknownAccountException(); //如果用户名错误
}
if(!"123".equals(password)) {
throw new IncorrectCredentialsException(); //如果密码错误
}
//如果身份认证验证成功,返回一个AuthenticationInfo实现;
return new SimpleAuthenticationInfo(username, password, getName());
}
}
package com.knife.Shiro.testRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
public class TestRealm {
public static void main(String args[]) {
// 1、获取SecurityManager工厂,此处使用Ini配置文件初始化SecurityManager
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shirorealm");
// 2、得到SecurityManager实例 并绑定给SecurityUtils
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
// 3、得到Subject及创建用户名/密码身份验证Token(即用户身份/凭证)
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("zhang", "123");
try {
// 4、登录,即身份验证
subject.login(token);
System.out.println("land success");
} catch (AuthenticationException e) {
// 5、身份验证失败
System.out.println("land faile,reason:" + e.getMessage());
}
// Assert.assertEquals(true, subject.isAuthenticated()); // 断言用户已经登录
// 6、退出
System.out.println("land state:" + subject.isAuthenticated());
subject.logout();
System.out.println("land state:" + subject.isAuthenticated());
}
}
结果
支持...
验证...
用户名:zhang 密码:123
land success
land state:true
land state:false
4.jdbcrealm
配置文件
jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealm
dataSource=com.alibaba.druid.pool.DruidDataSource
dataSource.driverClassName=com.mysql.jdbc.Driver
dataSource.url=jdbc:mysql://localhost:3306/shiro
dataSource.username=root
dataSource.password=HlztLhy
jdbcRealm.dataSource=$dataSource
jdbcRealm.permissionsLookupEnabled=true
securityManager.realms=$jdbcRealm
表结构
-- ----------------------------
-- Table structure for `roles_permissions`
-- ----------------------------
DROP TABLE IF EXISTS `roles_permissions`;
CREATE TABLE `roles_permissions` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`role_name` varchar(100) DEFAULT NULL,
`permission` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `idx_roles_permissions` (`role_name`,`permission`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of roles_permissions
-- ----------------------------
INSERT INTO `roles_permissions` VALUES ('1', 'admin', 'user:create');
INSERT INTO `roles_permissions` VALUES ('2', 'admin', 'user:update');
INSERT INTO `roles_permissions` VALUES ('3', 'role1', '+user1+10');
INSERT INTO `roles_permissions` VALUES ('5', 'role1', '+user2+10');
INSERT INTO `roles_permissions` VALUES ('7', 'role1', 'user1:create');
INSERT INTO `roles_permissions` VALUES ('6', 'role1', 'user2:*');
-- ----------------------------
-- Table structure for `users`
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`username` varchar(100) DEFAULT NULL,
`password` varchar(100) DEFAULT NULL,
`password_salt` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `idx_users_username` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of users
-- ----------------------------
INSERT INTO `users` VALUES ('1', 'zhang', '123', null);
INSERT INTO `users` VALUES ('2', 'li', '777', null);
-- ----------------------------
-- Table structure for `user_roles`
-- ----------------------------
DROP TABLE IF EXISTS `user_roles`;
CREATE TABLE `user_roles` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`username` varchar(100) DEFAULT NULL,
`role_name` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `idx_user_roles` (`username`,`role_name`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user_roles
-- ----------------------------
INSERT INTO `user_roles` VALUES ('2', 'li', 'admin');
INSERT INTO `user_roles` VALUES ('1', 'zhang', 'admin');
INSERT INTO `user_roles` VALUES ('3', 'zhang', 'role1');
INSERT INTO `user_roles` VALUES ('4', 'zhang', 'role2');
代码
package com.knife.Shiro.testJdbcRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
public class TestJdbcRealm {
public static void main(String args[]) {
// 1、获取SecurityManager工厂,此处使用Ini配置文件初始化SecurityManager
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:jdbcrealm");
// 2、得到SecurityManager实例 并绑定给SecurityUtils
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
// 3、得到Subject及创建用户名/密码身份验证Token(即用户身份/凭证)
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("zhang", "123");
try {
// 4、登录,即身份验证
subject.login(token);
System.out.println("land success");
} catch (AuthenticationException e) {
// 5、身份验证失败
System.out.println("land faile,reason:"+e.getMessage());
}
System.out.println("land state:"+subject.isAuthenticated());
System.out.println("has role:admin:"+subject.hasRole("admin"));
System.out.println("permitted :"+subject.isPermitted("user:update"));
subject.logout();
System.out.println("land state:"+subject.isAuthenticated());
}
}
结果
land success
land state:true
has role:admin:true
permitted :true
land state:false