Home Java javaTutorial Detailed introduction of shiro source code

Detailed introduction of shiro source code

Jul 26, 2017 pm 04:36 PM
shiro analyze Source code

(1)//1. Get the SecurityManager factory. Use the Ini configuration file to initialize the SecurityManager.
##Factory factory = new IniSecurityManagerFactory(" classpath:shiro.ini")
2. The class structure of the factory class is:

(3)The abstractFactory class mainly sets whether it is a singleton

(4)iniFactorySupport is an object created by supporting ini settings

(5)iniSecuritymanagerFactory is the implementation class of securityManager created in ini method

(2)//2. Get the SecurityManager instance and bind it to SecurityUtils
org.apache.shiro.mgt.SecurityManagersecurityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
(1) Create a Securitymanager object through the created Ini object

1

1  IniSecurityManagerFactory类:2      creatSecuritymanager(ini){3      SecurityManager securityManager = createSecurityManager(ini);4      return securityManager;5  }

Copy after login

(2) Create a Securitymanager through the created Ini object Object

1

 private SecurityManager createSecurityManager(Ini ini) { 2 //null 3 Ini.Section mainSection = ini.getSection(MAIN_SECTION_NAME); 4 if (CollectionUtils.isEmpty(mainSection)) { 5  6 //try the default: null 7 mainSection = ini.getSection(Ini.DEFAULT_SECTION_NAME); 8 } 9  return createSecurityManager(ini, mainSection);10  }

Copy after login

(3) Create Securitymanager

through the ini object and main module mainSession

1

 private SecurityManager createSecurityManager(Ini ini, Ini.Section mainSection) { 2 //{securityManager=DefaultSecurityManager,iniRealm=IniRealm}   3 Map defaults = createDefaults(ini, mainSection); 4 Map objects = buildInstances(mainSection, defaults); 5  6 SecurityManager securityManager = getSecurityManagerBean(); 7 boolean autoApplyRealms = isAutoApplyRealms(securityManager); 8 if (autoApplyRealms) { 9 //realms and realm factory might have been created - pull them out first  so we can initialize the securityManager:10  Collection realms = getRealms(objects);11  //set them on the SecurityManager12  if (!CollectionUtils.isEmpty(realms)) {13          applyRealmsToSecurityManager(realms, securityManager);14            }15         }16        return securityManager;17     }

Copy after login
(4) Set the association between objects through mainSession and the default object object

1

 private Map buildInstances(Ini.Section section, Map defaults) { 2      this.builder = new ReflectionBuilder(defaults); 3      return this.builder.buildObjects(section); 4      } 5 //类ReflectionBuilder 6 //通过mainSection创建对象并关联 7  public Map buildObjects(Map kvPairs) { 8   ..... 9  LifecycleUtils.init(objects.values());10 }

Copy after login
(5) Because IniRealm implements Initializable, initialize the IniRealm object

1

 //类IniRealm 2 private void processDefinitions(Ini ini) { 3  Ini.Section usersSection = ini.getSection(USERS_SECTION_NAME); 4  processUserDefinitions(usersSection); 5 } 6 //通过userSection解析user模块 7  protected void processUserDefinitions(Map userDefs) { 8       for (String username : userDefs.keySet()) { 9          ........10       account = new SimpleAccount(username, password, getName());11       add(account);12         ........13        }14  }15 protected void add(SimpleAccount account) {16    String username = getUsername(account);17    USERS_LOCK.writeLock().lock();18    try {19     this.users.put(username, account);20    }finally {21     USERS_LOCK.writeLock().unlock();22 }

Copy after login
The class structure of IniRealm is:

The structure of simpleAccount is:
##At this point, the object association is created. The initialization of IniRealm is completed! Next, look at the structure diagram of DefaultSecurityManager:
##(7) Set the realm attribute of DefaultSecurityManager:

1

1  applyRealmsToSecurityManager(realms, securityManager){2     ((RealmSecurityManager) securityManager).setRealms(realms);3 }4 //在类RealmSecurityManager中5 public void setRealms(Collection realms) {6    this.realms = realms;7    afterRealmsSet();8 }

Copy after login
Note:
afterRealmsSet(); is mainly used to set the realm attributes of authenticator and authorizer:

At this point, the properties of DefaultSecurityManager are set Complete and return the DefaultSecurityManager object
//3. Obtain the Subject and create the username/password authentication Token (i.e. user identity/credential)
Subject subject = SecurityUtils.getSubject();
##

1

//获取主题对象 2 public static Subject getSubject() {3     Subject subject = ThreadContext.getSubject();//第一次null4     if (subject == null) {5        subject = (new Subject.Builder()).buildSubject();6        ThreadContext.bind(subject);7         }8       return subject;9 }

Copy after login
(1) Code analysis: Use the builder pattern to create objects:

1

 public static class Builder{ 2        SubjectContext subjectContext; 3        SecurityManager securityManager; 4         public Builder(SecurityManager securityManager) { 5             if (securityManager == null) { 6                 throw new NullPointerException("SecurityManager method argument cannot be null."); 7             } 8             this.securityManager = securityManager; 9             this.subjectContext = newSubjectContextInstance();//DefaultSubjectContext(初始化一个backMap集合)10             if (this.subjectContext == null) {11                 throw new IllegalStateException("Subject instance returned from 'newSubjectContextInstance' " +12                         "cannot be null.");13             }14             this.subjectContext.setSecurityManager(securityManager);15         }16        public Subject buildSubject() {17             return this.securityManager.createSubject(this.subjectContext);18         }19 }

Copy after login

(2) Use the theme context to create a theme

1

 1   public Subject createSubject(SubjectContext subjectContext) { 2         //create a copy so we don't modify the argument's backing map: 3         SubjectContext context = copy(subjectContext); 4  5         //ensure that the context has a SecurityManager instance, and if not, add one: 6         context = ensureSecurityManager(context);//DefaultSubjectContext.backMap.put(SecurityManage) 7  8         //Resolve an associated Session (usually based on a referenced session ID), and place it in the context before 9         //sending to the SubjectFactory.  The SubjectFactory should not need to know how to acquire sessions as the10         //process is often environment specific - better to shield the SF from these details:11         context = resolveSession(context);12 13         //Similarly, the SubjectFactory should not require any concept of RememberMe - translate that here first14         //if possible before handing off to the SubjectFactory:15         context = resolvePrincipals(context);16 17         Subject subject = doCreateSubject(context);18 19         //save this subject for future reference if necessary:20         //(this is needed here in case rememberMe principals were resolved and they need to be stored in the21         //session, so we don't constantly rehydrate the rememberMe PrincipalCollection on every operation).22         //Added in 1.2:23         save(subject);24 25         return subject;26     }

Copy after login

(3) Create subject object through theme

1

2

 protected Subject doCreateSubject(SubjectContext context) {return getSubjectFactory().createSubject(context);

    }

Copy after login

 

(4)DefaultSubjectFactory创建主题对象:

1

 1    public Subject createSubject(SubjectContext context) { 2         SecurityManager securityManager = context.resolveSecurityManager(); 3         Session session = context.resolveSession(); 4         boolean sessionCreationEnabled = context.isSessionCreationEnabled(); 5         PrincipalCollection principals = context.resolvePrincipals(); 6         boolean authenticated = context.resolveAuthenticated(); 7         String host = context.resolveHost(); 8 9         return new DelegatingSubject(principals, authenticated, host, session, sessionCreationEnabled, securityManager);10     }

Copy after login

The above is the detailed content of Detailed introduction of shiro source code. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement data statistics and analysis in uniapp How to implement data statistics and analysis in uniapp Oct 24, 2023 pm 12:37 PM

How to implement data statistics and analysis in uniapp 1. Background introduction Data statistics and analysis are a very important part of the mobile application development process. Through statistics and analysis of user behavior, developers can have an in-depth understanding of user preferences and usage habits. Thereby optimizing product design and user experience. This article will introduce how to implement data statistics and analysis functions in uniapp, and provide some specific code examples. 2. Choose appropriate data statistics and analysis tools. The first step to implement data statistics and analysis in uniapp is to choose the appropriate data statistics and analysis tools.

How to display the source code of PHP code in the browser without being interpreted and executed? How to display the source code of PHP code in the browser without being interpreted and executed? Mar 11, 2024 am 10:54 AM

How to display the source code of PHP code in the browser without being interpreted and executed? PHP is a server-side scripting language commonly used to develop dynamic web pages. When a PHP file is requested on the server, the server interprets and executes the PHP code in it and sends the final HTML content to the browser for display. However, sometimes we want to display the source code of the PHP file directly in the browser instead of being executed. This article will introduce how to display the source code of PHP code in the browser without being interpreted and executed. In PHP, you can use

Analysis of the reasons why the secondary directory of DreamWeaver CMS cannot be opened Analysis of the reasons why the secondary directory of DreamWeaver CMS cannot be opened Mar 13, 2024 pm 06:24 PM

Title: Analysis of the reasons and solutions for why the secondary directory of DreamWeaver CMS cannot be opened. Dreamweaver CMS (DedeCMS) is a powerful open source content management system that is widely used in the construction of various websites. However, sometimes during the process of building a website, you may encounter a situation where the secondary directory cannot be opened, which brings trouble to the normal operation of the website. In this article, we will analyze the possible reasons why the secondary directory cannot be opened and provide specific code examples to solve this problem. 1. Possible cause analysis: Pseudo-static rule configuration problem: during use

Website to view source code online Website to view source code online Jan 10, 2024 pm 03:31 PM

You can use the browser's developer tools to view the source code of the website. In the Google Chrome browser: 1. Open the Chrome browser and visit the website where you want to view the source code; 2. Right-click anywhere on the web page and select "Inspect" or press the shortcut key Ctrl + Shift + I to open the developer tools; 3. In the top menu bar of the developer tools, select the "Elements" tab; 4. Just see the HTML and CSS code of the website.

Case analysis of Python application in intelligent transportation systems Case analysis of Python application in intelligent transportation systems Sep 08, 2023 am 08:13 AM

Summary of case analysis of Python application in intelligent transportation systems: With the rapid development of intelligent transportation systems, Python, as a multifunctional, easy-to-learn and use programming language, is widely used in the development and application of intelligent transportation systems. This article demonstrates the advantages and application potential of Python in the field of intelligent transportation by analyzing application cases of Python in intelligent transportation systems and giving relevant code examples. Introduction Intelligent transportation system refers to the use of modern communication, information, sensing and other technical means to communicate through

Analyze whether Tencent's main programming language is Go Analyze whether Tencent's main programming language is Go Mar 27, 2024 pm 04:21 PM

Title: Is Tencent’s main programming language Go: An in-depth analysis. As China’s leading technology company, Tencent has always attracted much attention in its choice of programming languages. In recent years, some people believe that Tencent mainly adopts Go as its main programming language. This article will conduct an in-depth analysis of whether Tencent's main programming language is Go, and give specific code examples to support this view. 1. Application of Go language in Tencent Go is an open source programming language developed by Google. Its efficiency, concurrency and simplicity are loved by many developers.

Analyze the advantages and disadvantages of static positioning technology Analyze the advantages and disadvantages of static positioning technology Jan 18, 2024 am 11:16 AM

Analysis of the advantages and limitations of static positioning technology With the development of modern technology, positioning technology has become an indispensable part of our lives. As one of them, static positioning technology has its unique advantages and limitations. This article will conduct an in-depth analysis of static positioning technology to better understand its current application status and future development trends. First, let’s take a look at the advantages of static positioning technology. Static positioning technology achieves the determination of position information by observing, measuring and calculating the object to be positioned. Compared with other positioning technologies,

A comprehensive guide to learning and applying golang framework source code A comprehensive guide to learning and applying golang framework source code Jun 01, 2024 pm 10:31 PM

By understanding the Golang framework source code, developers can master the essence of the language and expand the framework's functions. First, get the source code and become familiar with its directory structure. Second, read the code, trace the execution flow, and understand dependencies. Practical examples show how to apply this knowledge: create custom middleware and extend the routing system. Best practices include learning step-by-step, avoiding mindless copy-pasting, utilizing tools, and referring to online resources.

See all articles