• 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 抛出相应的中文提示即可

  • 相关阅读:
    【leetcode】153. 寻找旋转排序数组中的最小值
    vue下载网络图片
    前端开发项目细节
    如何在手机上预览本地h5页面
    react拖拽添加新组件
    js拖入并复制和拖动改变位置和改变大小
    dva model
    postMessage跨源通信
    react-router
    event.stopPropagation()和event.preventDefault(),return false的区别
  • 原文地址:https://www.cnblogs.com/xiaozhang666/p/12039143.html
Copyright © 2020-2023  润新知