Quick start code github.com/apache/shir…

Create the project first.Add the pom.xml contentGithub.com/apache/shir…

<? The XML version = "1.0" encoding = "utf-8"? > < 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" > < name > samples < / name > < the groupId > com. Shiro < / groupId > < artifactId > samples < / artifactId > < version > 1.0 - the SNAPSHOT < / version > The < modelVersion > 4.0.0 < / modelVersion > < packaging > war < / packaging > < dependencies > < the dependency > <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.4.0</version> </dependency> <! -- configure logging --> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>1.7.25</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId> slf44J -log4j12</artifactId> <version>1.7.25</version> <scope>runtime</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> <scope>runtime</scope> </dependency> </dependencies> </project>Copy the code

Paste log4j.properties and shiro.ini into resources github.com/apache/shir… Log4j. The properties file

# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the  License. # log4j.rootLogger=INFO, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %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=WARNCopy the code

Shiro ini file

# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the  License. # # ============================================================================= # Quickstart INI Realm configuration # # For those that might not understand the references in this file, the # definitions are all based on the classic Mel Brooks' film "Spaceballs". ;) # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = # ----------------------------------------------------------------------------- # Users and their assigned roles # # Each line conforms to the format defined in the # org.apache.shiro.realm.text.TextConfigurationRealm#setUserDefinitions JavaDoc # ----------------------------------------------------------------------------- [users] # user 'root' with password 'secret' and the 'admin' role root = secret, admin # user 'guest' with the password 'guest' and the 'guest' role guest = guest, guest # user 'presidentskroob' with password '12345' ("That's the same combination on # my luggage!!!" ;) ), and role 'president' presidentskroob = 12345, president # user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz' darkhelmet = ludicrousspeed, darklord, schwartz # user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz' lonestarr = vespa, goodguy #, schwartz # ----------------------------------------------------------------------------- # Roles with assigned permissions # # Each line conforms to the format defined in the # org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc # ----------------------------------------------------------------------------- [roles] # 'admin' role has all permissions, indicated by the wildcard '*' admin = * # The 'schwartz' role can do anything (*) with any lightsaber: schwartz = lightsaber:* # The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with # license plate 'eagle5' (instance specific id) goodguy = winnebago:drive:eagle5Copy the code

Create the Quickstart. Java github.com/apache/shir…

import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authc.credential.CredentialsMatcher; import org.apache.shiro.authc.credential.PasswordMatcher; import org.apache.shiro.authc.credential.SimpleCredentialsMatcher; 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; /** * @author: admin * @create: Public class Quickstart{static Logger Logger = loggerFactory.getLogger (quickstart.class); public static void main(String[] args) { Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); SecurityManager securityManager = factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); Subject subject = SecurityUtils.getSubject(); Session session = subject.getSession(); Session.setattribute ("name", "three "); String name = (String) session.getAttribute("name"); if (null ! = name) {logger.info(" get session name:" + name); } if (! Subject.isauthenticated ()) {logger.info(" not logged in, ready to log in..." ); UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa"); Object credentials = token.getCredentials(); try { subject.login(token); } catch (UnknownAccountException e) { e.printStackTrace(); Logger.info (" incorrect user name "); } catch (IncorrectCredentialsException e) { e.printStackTrace(); Logger.info (" password error "); } catch (AuthenticationException e) { e.printStackTrace(); }} logger.info(" logged in, logged in user "+ Subject.getPrincipal () + ","); If (subject.hasrole (" goodGuy ")) {logger.info(" user "+ Subject.getPrincipal () +" have permission goodGuy "); } else {logger.info(" user "+ Subject.getPrincipal () +" never had permission goodGuy "); } if (subject.ispermitted ("winnebago:drive:eagle5")) {logger.info(" user "+ subject.getPrincipal() + "Winnebago :drive:eagle5"); } else {logger.info(" user "+ Subject.getPrincipal () +" winnebago: Drive :eagle5"); } if (subject.ispermitted ("lightsaber:*")) {logger.info(" user "+ subject.getprincipal () +" Have permission lightsaber:*"); } else {logger.info(" user "+ subject.getPrincipal() +" never had secondary permission lightsaber:*"); } // subject.logout(); Logger.info (" User logged out successfully "); }}Copy the code

The code flow is really as simple as getting the SecurityManager to interact with the others

  1. Subject: represents the current user. This user is not necessarily a specific person, anything that interacts with the current application is a Subject, such as a web crawler, robot, etc. All subjects are bound to the SecurityManager, and all interactions with the Subject are delegated to the SecurityManager. We can think of the Subject as the facade and the SecurityManager as the actual enforcer.
  2. SecurityManager: SecurityManager. That is, all security-related operations interact with the SecurityManager, which manages all subjects. As you can see, this is the core of Shiro, and it is responsible for the interaction of other components.
  3. Realm: Shiro gets security data (such as users, roles, and permissions) from a Realm. This means that SecurityManager needs to authenticate the user, then it needs to get the corresponding user from the Realm and compare it to determine if the user is valid. You also need to get the user’s roles/permissions from the Realm to verify that the user can perform operations. You can configure more than one, but at least one

Subject. login is to login and authenticate through a realm and we’ll talk about that when we talk about shiro source code

  UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
 
                subject.login(token);
Copy the code