zoukankan      html  css  js  c++  java
  • 权限框架

    上篇文章中是使用的默认realm来实现的简单登录,这仅仅只是个demo,真正项目中使用肯定是需要连接数据库的

    首先创建自定义realm文件,如下:

    在shiro中注入自定义realm的完全限定类名:

    1 [main]
    2 # your custom realm path
    3 fooRealm=com.lee.shiro.realm.FooRealm
    4 # DI such as spring DI
    5 securityManager.realms=$fooRealm

    自定义realm认证:

     1     /**
     2      *  设置realm的名称
     3      */
     4     @Override
     5     public void setName(String name) {
     6         super.setName("fooRealm");
     7     }
     8 
     9     /**
    10      * 认证
    11      */
    12     @Override
    13     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    14 
    15         // token是用户输入的相关信息
    16         // 从token中取出身份信息, 即用户的username
    17         String username = (String)token.getPrincipal();
    18 
    19         // 根据用户名username从数据库查询密码password
    20         // 如果查询不到返回null
    21         // String password = userService.queryPwdByUserName(username)
    22         
    23         // 假设数据库查询出来的密码为如下
    24         String password = "1234567";
    25 
    26         // 如果查询到返回认证信息AuthenticationInfo
    27         SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username, password, this.getName());
    28 
    29         return simpleAuthenticationInfo;
    30     }

    执行认证:

        /**
         * 
         * @Description: 自定义realm
         * 
         * @author leechenxiang
         * @date 2016年6月11日 下午9:07:27
         */
        @Test
        public void testFooRealm() {
            // 创建SecurityManager工厂,通过ini配置文件创建 SecurityManager工厂
            Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro/shiro-realm.ini");
            // 创建SecurityManager
            SecurityManager securityManager = factory.getInstance();
            // 设置SecurityManager到运行环境中,保持单例模式
            SecurityUtils.setSecurityManager(securityManager);
            // 从SecurityUtils里边创建一个subject
            Subject subject = SecurityUtils.getSubject();
            // 在认证提交前准备token(令牌)
            // 这里的账号和密码 将来是由用户输入进去
            UsernamePasswordToken token = new UsernamePasswordToken("lee", "123456");
            try {
                // 执行认证提交
                subject.login(token);
            } catch (AuthenticationException e) {
                e.printStackTrace();
            }
            // 是否认证通过
            boolean isAuthenticated = subject.isAuthenticated();
            System.out.println("是否认证通过:" + isAuthenticated);
        }

    done...

  • 相关阅读:
    Tomcat目录结构及Tomcat Server处理一个http请求的过程
    JDBC
    Ajax
    Session总结
    request的setAttribute()怎么用的
    python中有多种标准输出格式,以下四种为常见的4种标准输出格式
    keywork模块查看当前环境所有关键字(保留字)
    props
    v-bind
    Vue指令
  • 原文地址:https://www.cnblogs.com/leechenxiang/p/5575968.html
Copyright © 2011-2022 走看看