shiro经典通俗易懂javase例子

package com.cun;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;



public class Quickstart {

    private static final Logger log = LoggerFactory.getLogger(Quickstart.class);


    public static void main(String[] args) {

     //创建配置的Shiro SecurityManager的最简单方法
     //领域,用户,角色和权限是使用简单的INI配置。
     //我们将通过使用可以提取.ini文件的工厂来实现这一点
      //返回一个SecurityManager实例

     //使用类路径根目录下的shiro.ini文件
     //(文件:和url:前缀分别从文件和网址加载):
        @SuppressWarnings("deprecation")
  Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();

      //对于这个简单的示例快速入门,请创建SecurityManager可作为JVM单例访问。 大多数应用程序不会这样做
      //而是依赖于他们的容器配置或web.xml webapps。
        SecurityUtils.setSecurityManager(securityManager);

      //现在设置了一个简单的Shiro环境,让我们看看你能做些什么:

       //获取当前执行的用户:
        Subject currentUser = SecurityUtils.getSubject();

       //用Session做一些事情(不需要web或EJB容器!!!)
        Session session = currentUser.getSession();
        session.setAttribute("sessionKey", "aValue");
        String value = (String) session.getAttribute("sessionKey");
        if (value!=null&&value.equals("aValue")) {
            log.info("检索正确的值: [" + value + "]");
        }else{
         log.info("检索错误的值: [" + value + "]");
        }

        //让我们登录当前用户,以便我们检查角色和权限:
        if (!currentUser.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken("admin", "123456");
            token.setRememberMe(true);
            try {
                currentUser.login(token);
            } catch (UnknownAccountException uae) {
                log.info("捕获未知用户名异常:" + token.getPrincipal());
            } catch (IncorrectCredentialsException ice) {
                log.info("捕获密码错误异常: " + token.getPrincipal());
            } catch (LockedAccountException lae) {
                log.info("账号锁住: " + token.getPrincipal());
            }catch (ExcessiveAttemptsException eae) {
             log.info("账号错误登录过多异常:: " + token.getPrincipal());
            }
          
            // ...在这里捕获更多例外(也许是特定于您的应用程序的自定义?
            catch (AuthenticationException ae) {
                //unexpected condition?  error?
            }
        }

        //判断是否登录成功:
        if(currentUser.getPrincipal()!=null)
        log.info("用户: [" + currentUser.getPrincipal() + "] 登录成功.");
               else
                  log.warn("登录失败!");
        //测试角色:
        if (currentUser.hasRole("schwartz")) {
            log.info("你有Schwartz角色!");
        } else {
            log.info("sorry,你只是普通用户没有Schwartz角色");
        }

        //测试有没该领域的权限
        if (currentUser.isPermitted("lightsaber:wield")) {
            log.info("你被许可:lightsaber:wield。明智地使用它.");
        } else {
            log.info("Sorry, lightsaber:wield访问域仅仅属于 schwartz角色.");
        }

        // (非常强大)实例级别权限:
        if (currentUser.isPermitted("winnebago:drive:eagle5")) {
            log.info("你被允许(id) 'eagle5'的'drive' winnebago  " +
                    "这是钥匙 - 玩得开心!");
        } else {
            log.info("Sorry,你不被允许'eagle5'winnebago!");
        }

        //退出
        currentUser.logout();

        System.exit(0);
    }
}
shiro.ini

[users]
root = 123, admin
guest = 123456, guest
presidentskroob = 123456, president
darkhelmet = 123456, darklord, schwartz
lonestarr = 123456, goodguy, schwartz


[roles]
admin = *
schwartz = lightsaber:*
goodguy = winnebago:drive:eagle5

log4j

  1. log4j
    log4j.rootLogger=INFO, stdout
    
     log4j.appender.stdout = org.apache.log4j.ConsoleAppender
     log4j.appender.stdout.Target = System.out
     log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
     log4j.appender.stdout.layout.ConversionPattern =  %d{ABSOLUTE} %5p %c{1}:%L - %m%n
    
    # General Apache libraries
    log4j.logger.org.apache=WARN
    
    # Spring
    log4j.logger.org.springframework=WARN
    
    # Default Shiro logging
    log4j.logger.org.apache.shiro=TRACE
    
    # Disable verbose logging
    log4j.logger.org.apache.shiro.util.ThreadContext=WARN
    log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN
    View Code

     

相对通用的maven

  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.11.RELEASE</version>
        <relativePath />
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        
        <!-- SpringBoot中使用 Shiro 做用户、角色、权限管理 -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.4.0</version>
        </dependency>
        
        <!-- swagger生成接口API -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>
        <!-- 接口API生成html文档 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.1</version>
        </dependency>
    </dependencies>
View Code

 

posted on 2019-04-22 10:06  Honey_Badger  阅读(418)  评论(0编辑  收藏  举报

导航

github