import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class DemoApacheShiro {

private static final transient Logger log = LoggerFactory.getLogger(DemoApacheShiro.class);


public static void main(String[] args) {

// The easiest way to create a Shiro SecurityManager with configured
// realms, users, roles and permissions is to use the shiro INI config.

Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();

SecurityUtils.setSecurityManager(securityManager);

// get the currently executing user
Subject currentUser = SecurityUtils.getSubject();

Session session = currentUser.getSession();
session.setAttribute("demo", "shiro_user");
String value = (String) session.getAttribute("demo");
if (value.equals("shiro_user")) {
log.info("Retrieved the correct value! [" + value + "]");
}

// let's login the current user so we can check against roles and permissions:
if (!currentUser.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken("shiro_user", "shiro_password");
token.setRememberMe(true);
try {
currentUser.login(token);
} catch (UnknownAccountException uae) {
log.info("There is no user with username of " + token.getPrincipal());
} catch (IncorrectCredentialsException ice) {
log.info("Password for account " + token.getPrincipal() + " was incorrect!");
} catch (LockedAccountException lae) {
log.info("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) {
log.info("AuthenticationException [" + ae.getMessage() + "]");
}
}

//print their identifying principal (in this case, a username):
log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

//test a role
if (currentUser.hasRole("shiro_role")) {
log.info("Shiro_role ok");
} else {
log.info("Shiro_role not ok");
}

//test a typed permission
if (currentUser.isPermitted("shiro_access")) {
log.info("You may use a shiro_access.");
} else {
log.info("Sorry, shiro_access not allowed.");
}

//log out
currentUser.logout();

System.exit(0);
}
}
