首页 > 代码库 > Shiro 的 HelloWorld

Shiro 的 HelloWorld

  • 密码文件
[users]zhang=123wang=123
  • 测试
package org.zln.hello;import org.apache.log4j.LogManager;import org.apache.log4j.Logger;import org.apache.shiro.SecurityUtils;import org.apache.shiro.authc.UsernamePasswordToken;import org.apache.shiro.config.IniSecurityManagerFactory;import org.apache.shiro.mgt.SecurityManager;import org.apache.shiro.subject.Subject;import org.apache.shiro.util.Factory;/** * Created by sherry on 16/9/8. */public class HelloWorld {    private static Logger logger = LogManager.getLogger(HelloWorld.class);    private static Subject subject;    static {        //1、获取 SecurityManager 工厂,此处使用 Ini 配置文件初始化 SecurityManager        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");        //2、得到 SecurityManager 实例 并绑定给 SecurityUtils        SecurityManager securityManager = factory.getInstance();        SecurityUtils.setSecurityManager(securityManager);        //3、得到 Subject 及创建用户名/密码身份验证 Token(即用户身份/凭证)        subject = SecurityUtils.getSubject();    }    public static boolean login(String username,String password){        UsernamePasswordToken token = new UsernamePasswordToken(username,password);        //4、登录,即身份验证        try {            subject.login(token);        }catch (Exception e){            logger.info("身份验证失败");            logger.error(e.getMessage(),e);            return false;        }        return subject.isAuthenticated();//是否成功登陆    }    public static void main(String[] args) {        //6、退出        subject.logout();    }}

 

默认使用 的 Relam 是 IniRelam

 

Shiro 的 HelloWorld