zoukankan      html  css  js  c++  java
  • shiro简单的认证功能

    使用静态shiro.ini文件完成认证

    创建项目到爆

         <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-core</artifactId>
                <version>1.4.1</version>
            </dependency>
            <!-- Shiro uses SLF4J for logging.  We'll use the 'simple' binding
                 in this example app.  See http://www.slf4j.org for more info. -->
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-simple</artifactId>
                <version>1.7.21</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>jcl-over-slf4j</artifactId>
                <version>1.7.21</version>
                <scope>test</scope>
            </dependency>

    核心的shiro和log4j依赖

    顺便创建log4j文件

    创建shiro.ini

    import org.apache.shiro.util.Factory;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    
    import org.apache.shiro.SecurityUtils;
    import org.apache.shiro.authc.AuthenticationToken;
    import org.apache.shiro.authc.UsernamePasswordToken;
    import org.apache.shiro.config.IniSecurityManagerFactory;
    import org.apache.shiro.mgt.SecurityManager;
    import org.apache.shiro.subject.Subject;
    
    public class TestAuthenticationApp {
        //日志输出工具
        private static final transient Logger log = LoggerFactory.getLogger(TestAuthenticationApp.class);
        public static void main(String[] args) {
            
             String username = "zhangsan";
             String password = "123456";
            
             log.info("My First Apache Shiro Application");
             //1 创建安全管理器的工厂对象
             Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
             //2 使用工厂创建安全管理器
             SecurityManager securityManager = factory.getInstance();
             //3 把当前的安全管理器绑定到线程
             SecurityUtils.setSecurityManager(securityManager);
             //4 使用SecurityUtils.getSubject() 得到主体
             Subject currentUser = SecurityUtils.getSubject();
            //5 封装用户名
             AuthenticationToken arg0 = new UsernamePasswordToken(username, password);
             currentUser.login(arg0);
             System.out.println("认证通过");
        }
    }

    当用户名或者密码不正确时,会抛出相应的异常

    使用cry cateh 抛出相应的中文提示即可

  • 相关阅读:
    对JavaScript调用堆栈和setTimeout用法的深入研究
    Js中的window.parent ,window.top,window.self 代表的对象
    lhgselect 联动选择下拉菜单 v1.0.0 (20110613)
    lhgcore JavaScript Library v1.4.5 API (20110622)
    表单元素完美垂直居中
    判断 iframe 是否加载完成的完美方法
    lhgdialog 弹出窗口插件 v3.5.2 ( 20110704 )
    JS的事件冒泡和事件捕获
    程序设计原则
    python中入口函数的用法
  • 原文地址:https://www.cnblogs.com/xiaozhang666/p/12039143.html
Copyright © 2011-2022 走看看