zoukankan      html  css  js  c++  java
  • Shiro理解与总结

    Feature

    Apache Shiro is a comprehensive application security framework with many features. The following diagram shows where Shiro focuses its energy, and this reference manual will be organized similarly:

    Shiro targets what the Shiro development team calls “the four cornerstones of application security” - Authentication, Authorization, Session Management, and Cryptography:

    • Authentication: Sometimes referred to as ‘login’, this is the act of proving a user is who they say they are.

    • Authorization: The process of access control, i.e. determining ‘who’ has access to ‘what’.

    • Session Management: Managing user-specific sessions, even in non-web or EJB applications.

    • Cryptography: Keeping data secure using cryptographic algorithms while still being easy to use.

    There are also additional features to support and reinforce these concerns in different application environments, especially:

    • Web Support: Shiro’s web support APIs help easily secure web applications.
    • Caching: Caching is a first-tier citizen in Apache Shiro’s API to ensure that security operations remain fast and efficient.
    • Concurrency: Apache Shiro supports multi-threaded applications with its concurrency features.
    • Testing: Test support exists to help you write unit and integration tests and ensure your code will be secured as expected.
    • “Run As”: A feature that allows users to assume the identity of another user (if they are allowed), sometimes useful in administrative scenarios.
    • “Remember Me”: Remember users’ identities across sessions so they only need to log in when mandatory.

    Architecture

    • Subject (org.apache.shiro.subject.Subject)
      A security-specific ‘view’ of the entity (user, 3rd-party service, cron job, etc) currently interacting with the software.

    • SecurityManager (org.apache.shiro.mgt.SecurityManager)
      As mentioned above, the SecurityManager is the heart of Shiro’s architecture. It is mostly an ‘umbrella’ object that coordinates its managed components to ensure they work smoothly together. It also manages Shiro’s view of every application user, so it knows how to perform security operations per user.

    • Authenticator (org.apache.shiro.authc.Authenticator)
      The Authenticator is the component that is responsible for executing and reacting to authentication (log-in) attempts by users. When a user tries to log-in, that logic is executed by the Authenticator. The Authenticator knows how to coordinate with one or more Realms that store relevant user/account information. The data obtained from these Realms is used to verify the user’s identity to guarantee the user really is who they say they are.

      • Authentication Strategy (org.apache.shiro.authc.pam.AuthenticationStrategy)
        If more than one Realm is configured, the AuthenticationStrategy will coordinate the Realms to determine the conditions under which an authentication attempt succeeds or fails (for example, if one realm succeeds but others fail, is the attempt successful? Must all realms succeed? Only the first?).

    • Authorizer (org.apache.shiro.authz.Authorizer)
      The Authorizer is the component responsible determining users’ access control in the application. It is the mechanism that ultimately says if a user is allowed to do something or not. Like the Authenticator, the Authorizer also knows how to coordinate with multiple back-end data sources to access role and permission information. The Authorizer uses this information to determine exactly if a user is allowed to perform a given action.

    • SessionManager (org.apache.shiro.session.mgt.SessionManager)
      The SessionManager knows how to create and manage user Session lifecycles to provide a robust Session experience for users in all environments. This is a unique feature in the world of security frameworks - Shiro has the ability to natively manage user Sessions in any environment, even if there is no Web/Servlet or EJB container available. By default, Shiro will use an existing session mechanism if available, (e.g. Servlet Container), but if there isn’t one, such as in a standalone application or non-web environment, it will use its built-in enterprise session management to offer the same programming experience. The SessionDAO exists to allow any datasource to be used to persist sessions.

      • SessionDAO (org.apache.shiro.session.mgt.eis.SessionDAO)
        The SessionDAO performs Session persistence (CRUD) operations on behalf of the SessionManager. This allows any data store to be plugged in to the Session Management infrastructure.

    • CacheManager (org.apache.shiro.cache.CacheManager)
      The CacheManager creates and manages Cache instance lifecycles used by other Shiro components. Because Shiro can access many back-end data sources for authentication, authorization and session management, caching has always been a first-class architectural feature in the framework to improve performance while using these data sources. Any of the modern open-source and/or enterprise caching products can be plugged in to Shiro to provide a fast and efficient user-experience.

    • Cryptography (org.apache.shiro.crypto.*)
      Cryptography is a natural addition to an enterprise security framework. Shiro’s crypto package contains easy-to-use and understand representations of crytographic Ciphers, Hashes (aka digests) and different codec implementations. All of the classes in this package are carefully designed to be very easy to use and easy to understand. Anyone who has used Java’s native cryptography support knows it can be a challenging animal to tame. Shiro’s crypto APIs simplify the complicated Java mechanisms and make cryptography easy to use for normal mortal human beings.

    • Realms (org.apache.shiro.realm.Realm)
      As mentioned above, Realms act as the ‘bridge’ or ‘connector’ between Shiro and your application’s security data. When it comes time to actually interact with security-related data like user accounts to perform authentication (login) and authorization (access control), Shiro looks up many of these things from one or more Realms configured for an application. You can configure as many Realms as you need (usually one per data source) and Shiro will coordinate with them as necessary for both authentication and authorization.

    Shiro example

    java:

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

    pom:

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     3     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
     4 
     5     <modelVersion>4.0.0</modelVersion>
     6     <groupId>org.apache.shiro.tutorials</groupId>
     7     <artifactId>shiro-tutorial</artifactId>
     8     <version>1.0.0-SNAPSHOT</version>
     9     <name>First Apache Shiro Application</name>
    10     <packaging>jar</packaging>
    11 
    12     <properties>
    13         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    14     </properties>
    15 
    16     <build>
    17         <plugins>
    18             <plugin>
    19                 <groupId>org.apache.maven.plugins</groupId>
    20                 <artifactId>maven-compiler-plugin</artifactId>
    21                 <version>2.0.2</version>
    22                 <configuration>
    23                     <source>1.5</source>
    24                     <target>1.5</target>
    25                     <encoding>${project.build.sourceEncoding}</encoding>
    26                 </configuration>
    27             </plugin>
    28 
    29             <!-- This plugin is only to test run our little application. It is not 
    30                 needed in most Shiro-enabled applications: -->
    31             <plugin>
    32                 <groupId>org.codehaus.mojo</groupId>
    33                 <artifactId>exec-maven-plugin</artifactId>
    34                 <version>1.1</version>
    35                 <executions>
    36                     <execution>
    37                         <goals>
    38                             <goal>java</goal>
    39                         </goals>
    40                     </execution>
    41                 </executions>
    42                 <configuration>
    43                     <classpathScope>test</classpathScope>
    44                     <mainClass>Tutorial</mainClass>
    45                 </configuration>
    46             </plugin>
    47         </plugins>
    48     </build>
    49 
    50     <dependencies>
    51         <dependency>
    52             <groupId>org.apache.shiro</groupId>
    53             <artifactId>shiro-core</artifactId>
    54             <version>1.1.0</version>
    55         </dependency>
    56         <!-- Shiro uses SLF4J for logging. We'll use the 'simple' binding in this 
    57             example app. See http://www.slf4j.org for more info. -->
    58          <dependency>
    59        <groupId>org.slf4j</groupId>
    60        <artifactId>slf4j-api</artifactId>
    61        <version>1.7.5</version>
    62    </dependency>
    63    <dependency>
    64        <groupId>org.slf4j</groupId>
    65        <artifactId>slf4j-simple</artifactId>
    66        <version>1.6.4</version>
    67    </dependency>
    68 
    69     </dependencies>
    70 
    71 </project>

    output:

    0 [main] INFO com.hjp.shiro.shiro_tutorial.Tutorial - My First Apache Shiro Application
    26582 [main] INFO org.apache.shiro.session.mgt.AbstractValidatingSessionManager - Enabling session validation scheduler...
    44789 [main] INFO com.hjp.shiro.shiro_tutorial.Tutorial - Retrieved the correct value! [aValue]
    80397 [main] INFO com.hjp.shiro.shiro_tutorial.Tutorial - User [lonestarr] logged in successfully.
    85201 [main] INFO com.hjp.shiro.shiro_tutorial.Tutorial - May the Schwartz be with you!
    90551 [main] INFO com.hjp.shiro.shiro_tutorial.Tutorial - You may use a lightsaber ring.  Use it wisely.
    95185 [main] INFO com.hjp.shiro.shiro_tutorial.Tutorial - You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  Here are the keys - have fun!

     Refer

    http://shiro.apache.org/architecture.html

     

  • 相关阅读:
    python 安装pillow
    rapidminer 数据导入及几个算子简单应用
    Fiddler高级用法-设置断点
    Linux 操作MySQL常用命令行
    VMWare虚拟机提示:另一个程序已锁定文件的一部分,打不开磁盘...模块"Disk"启动失败的解决办法
    解决VMware15 centos7 桥接模式ssh突然不能访问的问题
    新媒体运营需要什么能力?需要具备哪些运营技能?
    运营分为哪几类?具体的工作职责是什么?
    Centos7 yum安装MySQL5.7.25
    Centos7防火墙添加端口
  • 原文地址:https://www.cnblogs.com/huangjianping/p/7943481.html
Copyright © 2011-2022 走看看