package util;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MySecurityManager {
private static transient final Logger log = LoggerFactory.getLogger(MySecurityManager.class);
public static boolean login(String username, String password) {
boolean isLogin = false;
try {
AuthenticationToken token = new UsernamePasswordToken(username, password);
Subject currentUser = SecurityUtils.getSubject();
currentUser.login(token);
isLogin = true;
} catch (AuthenticationException e) {
log.error("login fail!,case as ", e);
}
return isLogin;
}
public static void logout() {
Subject currentUser = SecurityUtils.getSubject();
currentUser.logout();
}
public static Object getSessionAttribute(String key) {
Subject currentUser = SecurityUtils.getSubject();
Session session = currentUser.getSession(false);
return (session != null ? session.getAttribute(key) : null);
}
public static void setSessionAttribute(String name, Object value) {
Subject currentUser = SecurityUtils.getSubject();
if (value != null) {
Session session = currentUser.getSession();
session.setAttribute(name, value);
} else {
Session session = currentUser.getSession(false);
session.removeAttribute(name);
}
}
}