Java tutorial
package com.yimeicloud.study.shiro; 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.config.IniSecurityManagerFactory; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.session.Session; import org.apache.shiro.subject.Subject; import org.apache.shiro.util.Factory; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class QuickStart { private static final transient Logger log = LoggerFactory.getLogger(QuickStart.class); // @BeforeClass public static void beforeClass() { }; // @AfterClass public static void afterClass() { }; // ??? @Before public void before() { } // ??? @After public void after() { } @Test public void runTest() { // ?SecurityManagerini??SecurityManager Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); // ?SecurityManagerSecurityUtils SecurityManager securityManager = factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); // ?? Subject currentUser = SecurityUtils.getSubject(); // ?session Session session = currentUser.getSession(); session.setAttribute("someKey", "aValue"); String value = (String) session.getAttribute("someKey"); if ("aValue".equals(value)) { log.info("Retrieved the correct value![" + value + "]"); } // ? UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa"); // try { currentUser.login(token); } catch (UnknownAccountException e) { log.info("??"); } catch (IncorrectCredentialsException e) { log.info("?"); } catch (LockedAccountException e) { log.info("??"); } catch (AuthenticationException e) { log.info("?"); } // ? if (currentUser.isAuthenticated()) { log.info("?..."); } else { log.info("?..."); } // test role if (currentUser.hasRole("goodguy")) { log.info("May the Schwartz be with you!"); } else { log.info("Hello, mere mortal."); } //test a typed permission (not instance-level) if (currentUser.isPermitted("lightsaber:weild")) { log.info("You may use a lightsaber ring. Use it wisely."); } else { log.info("Sorry, lightsaber rings are for schwartz masters only."); } //a (very powerful) Instance Level permission: if (currentUser.isPermitted("winnebago:drive:eagle5")) { log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " + "Here are the keys - have fun!"); } else { log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!"); } // currentUser.logout(); } }