首页 > 技术文章 > shiro实例(一) 非web版

albert-think 2017-03-23 16:20 原文

转载地址:https://my.oschina.net/Tsher2015/blog/655132

import javax.naming.AuthenticationException;
import org.apache.shiro.SecurityUtils;
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.apache.shiro.util.ThreadContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ShrioDemo {
    
    private static final Logger logger=LoggerFactory.getLogger(ShrioDemo.class);

    public static void main(String[] args) throws AuthenticationException {
        //初始化 SecurityManager(配置文件放在根目录下)
        Factory<SecurityManager> factory=new IniSecurityManagerFactory("classpath:shiro.ini");
        
        SecurityManager securityManager=factory.getInstance();
        
        SecurityUtils.setSecurityManager(securityManager);
        //设置参数
        Subject currentUser=SecurityUtils.getSubject();
        
        Session session=currentUser.getSession();
        
        session.setAttribute("userInfo", "rayn");
        
        String value=(String)session.getAttribute("userInfo");
        
        //判断
        if(value.equals("rayn")){
            
            logger.info("Retrieved the correct value!["+value+"]");
        }
        //
        UsernamePasswordToken token=null;
        
        if(!currentUser.isAuthenticated()){
            
            token= new UsernamePasswordToken("liu","123123",false);
            
            try{
                
                currentUser.login(token);
                
            }catch(UnknownAccountException uae){
                
                logger.info("不存在用户名为:"+token.getPrincipal());
            
            }catch(IncorrectCredentialsException ice){
                
                logger.info("用户:["+token.getPrincipal()+"]的密码错误");
                
            }catch(LockedAccountException lae){
                
                logger.info("该用户已经锁定["+token.getPrincipal()+"请联系管理员进行解锁");
            }
        }
        logger.info("用户 ["+currentUser.getPrincipal()+"]登陆成功!");
        
        //currentUser = SecurityUtils.getSubject();
        
        if(currentUser.hasRole("admin")){
            
            logger.info("该用户为admin.");
            
        }else{

            logger.info("没有角色");
        }
        if(currentUser.isPermitted("users:del")){
            
            logger.info("拥有: users:del");
            
        }else{
            
            logger.info("没有权限");
            
        }if (currentUser.isPermitted("users:create:del:upd"))
        {
            logger.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " + "Here are the keys - have fun!");
        }
        else
        {
            logger.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
        }
        //在非web开发下可以不加,在web开发下需要添加
        //当前用户退出
        currentUser.logout();
        //退出时解除绑定Subject到线程 否则对下次测试造成影响
        ThreadContext.unbindSubject();
        //1.System.exit(0)是将你的整个虚拟机里的内容都停掉了,而dispose()只是关闭这个窗口,但是并没有停止整个application exit().无论如何,内存都释放了!也就是说连JVM都关闭了,内存里根本不可能还有什么东西
        //2.System.exit(0)是正常退出程序,而System.exit(1)或者说非0表示非正常退出程序
        //3.System.exit(status)不管status为何值都会退出程序。和return 相比有以下不同点: return是回到上一层,而System.exit(status)是回到最上层
        System.exit(0);
        
    }

}

 配置文件:

[users]
lh=123123,user
liu=123123,admin
rayn=111,guest

[roles]
admin = *
user =users:create:del:upd
guest = guest:*

[urls]
/index.html = anon
/** = authc

输出结果:
四月 08, 2016 3:05:45 下午 org.apache.shiro.session.mgt.AbstractValidatingSessionManager enableSessionValidation
信息: Enabling session validation scheduler...
四月 08, 2016 3:05:46 下午 com.ninemax.application.shiro.example.ShrioDemo main
信息: Retrieved the correct value![rayn]
四月 08, 2016 3:05:46 下午 com.ninemax.application.shiro.example.ShrioDemo main
信息: 用户 [liu]登陆成功!
四月 08, 2016 3:05:46 下午 com.ninemax.application.shiro.example.ShrioDemo main
信息: 该用户为admin.
四月 08, 2016 3:05:46 下午 com.ninemax.application.shiro.example.ShrioDemo main
信息: 拥有: users:del
四月 08, 2016 3:05:46 下午 com.ninemax.application.shiro.example.ShrioDemo main
信息: You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  Here are the keys - have fun!

推荐阅读