身份认证功能chiro的使用

时间:2020-12-12 07:26:00

package com.cun;
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 Quickstart {

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

public static void main(String[] args) {

@SuppressWarnings("deprecation")
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");         //通过chiro创建一个工厂
SecurityManager securityManager = factory.getInstance();                         //通过工厂factory.getInstance创建一个SecurityManager对象,

SecurityUtils.setSecurityManager(securityManager);         //设置安全信息setSecurityManager(securityManager)

//现在设置了一个简单的Shiro环境,让我们看看你能做些什么:

//获取当前执行的用户:
Subject currentUser = SecurityUtils.getSubject();             //通过创建的SecurityUtils.getdubject获取当前正在执行的用户

Session session = currentUser.getSession();        //通过当前用户情况创建一个会话
session.setAttribute("sessionKey", "aValue");           //设置会话的属性保存在某个值中
String value = (String) session.getAttribute("sessionKey");        //得到会话的值
if (value!=null&&value.equals("aValue")) {
log.info("检索正确的值: [" + value + "]");
}else{
log.info("检索错误的值: [" + value + "]");
}

//让我们登录当前用户,以便我们检查角色和权限:
if (!currentUser.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken("admin", "123456");
token.setRememberMe(true);
try {
currentUser.login(token);
} catch (UnknownAccountException uae) {
log.info("捕获未知用户名异常:" + token.getPrincipal());
} catch (IncorrectCredentialsException ice) {
log.info("捕获密码错误异常: " + token.getPrincipal());
} catch (LockedAccountException lae) {
log.info("账号锁住: " + token.getPrincipal());
}catch (ExcessiveAttemptsException eae) {
log.info("账号错误登录过多异常:: " + token.getPrincipal());
}

// ...在这里捕获更多例外(也许是特定于您的应用程序的自定义?
catch (AuthenticationException ae) {
//unexpected condition? error?
}
}

//判断是否登录成功:
if(currentUser.getPrincipal()!=null)
log.info("用户: [" + currentUser.getPrincipal() + "] 登录成功.");
else
log.warn("登录失败!");
//测试角色:
if (currentUser.hasRole("schwartz")) {
log.info("你有Schwartz角色!");
} else {
log.info("sorry,你只是普通用户没有Schwartz角色");
}

//测试有没该领域的权限
if (currentUser.isPermitted("lightsaber:wield")) {
log.info("你被许可:lightsaber:wield。明智地使用它.");
} else {
log.info("Sorry, lightsaber:wield访问域仅仅属于 schwartz角色.");
}

// (非常强大)实例级别权限:
if (currentUser.isPermitted("winnebago:drive:eagle5")) {
log.info("你被允许(id) 'eagle5'的'drive' winnebago " +
"这是钥匙 - 玩得开心!");
} else {
log.info("Sorry,你不被允许'eagle5'winnebago!");
}

//退出
currentUser.logout();

System.exit(0);
}
}