内部结构框架
#创建对象 securityManager=org.apache.shiro.mgt.DefaultSecurityManager
[users] zhang=123,role1,role2 wang=123
[roles] role1=user:create,user:update role2=*
/index.html = anon /admin/** = authc, roles[admin],perms["permission1"]
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.1.0</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.6.1</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency>
[users] root = 123456 # 账号为root 密码是 123456
认证操作
@Test public void test() { // 1.获取SecurityManager工厂对象 Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); // 2.通过Factory对象获取SecurityManager对象 SecurityManager securityManager = factory.getInstance(); // 3.将SecurityManager对象添加到当前运行环境中 SecurityUtils.setSecurityManager(securityManager); // 4.获取Subject对象 Subject subject = SecurityUtils.getSubject(); AuthenticationToken token = new UsernamePasswordToken("root", "123456"); // 登录操作 subject.login(token); // 获取登录的状态 System.out.println(subject.isAuthenticated()); }
@Test public void test() { // 1.获取SecurityManager工厂对象 Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); // 2.通过Factory对象获取SecurityManager对象 SecurityManager securityManager = factory.getInstance(); // 3.将SecurityManager对象添加到当前运行环境中 SecurityUtils.setSecurityManager(securityManager); // 4.获取Subject对象 Subject subject = SecurityUtils.getSubject(); AuthenticationToken token = new UsernamePasswordToken("root", "111"); // 登录操作 try { subject.login(token); } catch (UnknownAccountException e) { System.out.println("账号出错..."); } catch(IncorrectCredentialsException e){ System.out.println("密码出错..."); } // 获取登录的状态 System.out.println(subject.isAuthenticated()); }
认证流程总结