shiro示例讲解

        官网shiro例子,可以很好的帮助我们理解和运用shiro。下面就讲解下怎么如何使用maven来运行官网示例,及理解其实现过程。

        一、新建maven项目

      new->other->Maven project->Create a simple project (勾选)

       

   二、新建shiro文件(shiro.ini),放入src/main/resources路径下,log4j.properties也是放入该路径下。

        

 1 # =============================================================================
 2 # Tutorial INI configuration
 3 #
 4 # Usernames/passwords are based on the classic Mel Brooks' film "Spaceballs" :)
 5 # =============================================================================
 6 
 7 # -----------------------------------------------------------------------------
 8 # Users and their (optional) assigned roles
 9 # username = password, role1, role2, ..., roleN
10 # -----------------------------------------------------------------------------
11 [users]
12 root = secret, admin
13 guest = guest, guest
14 presidentskroob = 12345, president
15 darkhelmet = ludicrousspeed, darklord, schwartz
16 lonestarr = vespa, goodguy, schwartz
17 
18 # -----------------------------------------------------------------------------
19 # Roles with assigned permissions
20 # roleName = perm1, perm2, ..., permN
21 # -----------------------------------------------------------------------------
22 [roles]
23 admin = *
24 schwartz = lightsaber:*
25 goodguy = winnebago:drive:eagle5
View Code

 三、pom.xml文件配置

       1、引入shiro的相关jar包,shiro依赖slf4j包,这里也可引入下。

         

        

            注意:shiro-core 高版本的jar包,已经不支持读取配置文件这种方式了。项目中低版本1.2.4的是支持的。

       2、要执行main函数,这里引入maven-compiler-plugin插件和exec-maven-plugin插件。其中exec-maven-plugin插件配置中需指定执行main函数所在类的路径

          

     具体pom.xml配置参考如下:

   

 1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 2   <modelVersion>4.0.0</modelVersion>
 3   <groupId>com.hik.shiro.tutorial</groupId>
 4   <artifactId>shiro-tutorial</artifactId>
 5   <version>0.0.1-SNAPSHOT</version>
 6   <name>First Apache Shiro Application</name>
 7   <description>First Apache Shiro Application</description>
 8   
 9   <properties>
10         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
11     </properties>
12     
13      <build>
14         <plugins>
15             <plugin>
16                 <groupId>org.apache.maven.plugins</groupId>
17                 <artifactId>maven-compiler-plugin</artifactId>
18                 <version>3.6.1</version>
19                 <configuration>
20                     <source>1.7</source>
21                     <target>1.7</target>
22                     <encoding>${project.build.sourceEncoding}</encoding>
23                 </configuration>
24             </plugin>
25 
26         <!-- This plugin is only to test run our little application.  It is not
27              needed in most Shiro-enabled applications: -->
28             <plugin>
29                 <groupId>org.codehaus.mojo</groupId>
30                 <artifactId>exec-maven-plugin</artifactId>
31                 <version>1.6.0</version>
32                 <executions>
33                     <execution>
34                         <goals>
35                             <goal>java</goal>
36                         </goals>
37                     </execution>
38                 </executions>
39                 <configuration>
40                     <classpathScope>test</classpathScope>
41                     <mainClass>shiro.Tutorial</mainClass>
42                 </configuration>
43             </plugin>
44         </plugins>
45     </build>
46   
47   <dependencies>
48       <dependency>
49         <groupId>org.apache.shiro</groupId>
50         <artifactId>shiro-core</artifactId>
51         <version>1.2.4</version>
52     </dependency>
53       <dependency>
54         <groupId>org.slf4j</groupId>
55         <artifactId>slf4j-log4j12</artifactId>
56         <version>1.7.25</version>
57         <scope>test</scope>
58     </dependency>
59   </dependencies>
60 </project>
View Code

四、Tutorial.java文件

     

 1 package shiro;
 2 
 3 import org.apache.shiro.SecurityUtils;
 4 import org.apache.shiro.authc.AuthenticationException;
 5 import org.apache.shiro.authc.IncorrectCredentialsException;
 6 import org.apache.shiro.authc.LockedAccountException;
 7 import org.apache.shiro.authc.UnknownAccountException;
 8 import org.apache.shiro.authc.UsernamePasswordToken;
 9 import org.apache.shiro.config.IniSecurityManagerFactory;
10 import org.apache.shiro.mgt.SecurityManager;
11 import org.apache.shiro.session.Session;
12 import org.apache.shiro.subject.Subject;
13 import org.apache.shiro.util.Factory;
14 import org.slf4j.Logger;
15 import org.slf4j.LoggerFactory;
16 
17 /**
18  * 
19  */
20 
21 /**
22  * @ClassName: Tutorial
23  * @Description: TODO
24  * @author jed
25  * @date 2017��7��8������4:27:52
26  *
27  */
28 public class Tutorial {
29     
30     private static final transient Logger log = LoggerFactory.getLogger(Tutorial.class);
31     
32     public static void main(String[] args) {
33         // 读取配置文件,初始化SecurityManager工厂
34         Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
35         // 获取securityManager实例
36         SecurityManager securityManager = factory.getInstance();
37         // 把securityManager实例绑定到SecurityUtils
38         SecurityUtils.setSecurityManager(securityManager);
39         // get the currently executing user:
40         Subject currentUser = SecurityUtils.getSubject();
41         // Do some stuff with a Session (no need for a web or EJB container!!!)
42         Session session = currentUser.getSession();
43         session.setAttribute("someKey", "aValue");
44         String value = (String) session.getAttribute("someKey");
45         if(value.equals("aValue")){
46             log.info("Retrieved the correct value! [" + value + "]");
47         }
48         
49         // let's login the current user so we can check against roles and permissions:
50         if(!currentUser.isAuthenticated()){
51             UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
52             token.setRememberMe(true);
53             try {
54                 currentUser.login(token);
55             } catch(UnknownAccountException uae){
56                 log.info("There is no user with username of " + token.getPrincipal());
57             }catch(IncorrectCredentialsException ice ){
58                  log.info("Password for account " + token.getPrincipal() + " was incorrect!");
59             }catch (LockedAccountException lae) {
60                 log.info("The account for username " + token.getPrincipal() + " is locked.  " +
61                         "Please contact your administrator to unlock it.");
62             }catch (AuthenticationException ae) {// ... catch more exceptions here (maybe custom ones specific to your application?
63                 //unexpected condition?  error?
64             }
65         }
66         
67          //say who they are:
68         //print their identifying principal (in this case, a username):
69         log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
70         
71         //test a role:
72         if(currentUser.hasRole("schwartz")){
73              log.info("May the Schwartz be with you!");
74         }else{
75             log.info("Hello, mere mortal.");
76         }
77         
78        //test a typed permission (not instance-level)
79         if(currentUser.isPermitted("lightsaber:weild")){
80              log.info("You may use a lightsaber ring.  Use it wisely.");
81         }else {
82              log.info("Sorry, lightsaber rings are for schwartz masters only.");
83         }
84         
85       //a (very powerful) Instance Level permission:
86         
87         if(currentUser.isPermitted("winnebago:drive:eagle5")){
88              log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " +
89                      "Here are the keys - have fun!");
90         }else {
91             log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
92         }
93         
94         //all done - log out!
95         currentUser.logout();
96         
97         System.exit(0);
98     }
99 }
View Code

五、eclipse执行shiro示例项目配置

  

重要提示:pom.xml配置文件中引入依赖的jar版本,及更新新的jar包版本号,可到中央仓库查询。

中央仓库
http://mvnrepository.com/

     

            

原文地址:https://www.cnblogs.com/jedjia/p/shiro-maven.html