### Shiro Quickstart Example Source: https://shiro.apache.org/static/2.0.0/cpd.html This Java code demonstrates a basic Shiro quickstart, including setting up the SecurityManager, using sessions, logging in users, and checking roles and permissions. It's intended for simple examples and might not reflect production-ready configurations. ```java SecurityManager securityManager = injector.getInstance(SecurityManager.class); // for this simple example quickstart, make the SecurityManager // accessible as a JVM singleton. Most applications wouldn't do this // and instead rely on their container configuration or web.xml for // webapps. That is outside the scope of this simple quickstart, so // we'll just do the bare minimum so you can continue to get a feel // for things. SecurityUtils.setSecurityManager(securityManager); // Now that a simple Shiro environment is set up, let's see what you can do: // get the currently executing user: Subject currentUser = SecurityUtils.getSubject(); // Do some stuff with a Session (no need for a web or EJB container!!!) Session session = currentUser.getSession(); session.setAttribute("someKey", "aValue"); String value = (String) session.getAttribute("someKey"); if (value.equals("aValue")) { log.info("Retrieved the correct value! [" + value + "]"); } // let's login the current user so we can check against roles and permissions: if (!currentUser.isAuthenticated()) { UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa"); token.setRememberMe(true); try { currentUser.login(token); } catch (UnknownAccountException uae) { log.info("There is no user with username of " + token.getPrincipal()); } catch (IncorrectCredentialsException ice) { log.info("Password for account " + token.getPrincipal() + " was incorrect!"); } catch (LockedAccountException lae) { log.info("The account for username " + token.getPrincipal() + " is locked. " + "Please contact your administrator to unlock it."); } // ... catch more exceptions here (maybe custom ones specific to your application? catch (AuthenticationException ae) { //unexpected condition? error? } } //say who they are: //print their identifying principal (in this case, a username): log.info("User [" + currentUser.getPrincipal() + "] logged in successfully."); //test a role: if (currentUser.hasRole("schwartz")) { log.info("May the Schwartz be with you!"); } else { log.info("Hello, mere mortal."); } //test a typed permission (not instance-level) if (currentUser.isPermitted("lightsaber:wield")) { log.info("You may use a lightsaber ring. Use it wisely."); } else { log.info("Sorry, lightsaber rings are for schwartz masters only."); } //a (very powerful) Instance Level permission: if (currentUser.isPermitted("winnebago:drive:eagle5")) { log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " + "Here are the keys - have fun!"); } else { log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!"); } //all done - log out! currentUser.logout(); System.exit(0); } } ``` -------------------------------- ### Spring Boot QuickStart Example Source: https://shiro.apache.org/static/2.0.0/cpd.html Demonstrates basic Shiro authentication and authorization in a Spring Boot application. It logs in a user, checks roles and permissions, and attempts restricted method calls. ```java @Component public class QuickStart { private static Logger log = LoggerFactory.getLogger(QuickStart.class); @Autowired private SecurityManager securityManager; @Autowired private SimpleService simpleService; public void run() { // get the current subject Subject subject = SecurityUtils.getSubject(); // Subject is not authenticated yet Assert.isTrue(!subject.isAuthenticated()); // login the subject with a username / password UsernamePasswordToken token = new UsernamePasswordToken("joe.coder", "password"); subject.login(token); // joe.coder has the "user" role subject.checkRole("user"); // joe.coder does NOT have the admin role Assert.isTrue(!subject.hasRole("admin")); // joe.coder has the "read" permission subject.checkPermission("read"); // current user is allowed to execute this method. simpleService.readRestrictedCall(); try { // but not this one! simpleService.writeRestrictedCall(); } catch (AuthorizationException e) { log.info("Subject was NOT allowed to execute method 'writeRestrictedCall'"); } // logout subject.logout(); Assert.isTrue(!subject.isAuthenticated()); } /** * Sets the static instance of SecurityManager. This is NOT needed for web applications. */ @PostConstruct private void initStaticSecurityManager() { SecurityUtils.setSecurityManager(securityManager); } } ``` -------------------------------- ### Navigate to Shiro Quickstart Directory Source: https://shiro.apache.org/10-minute-tutorial.html Changes the current directory to the Shiro quickstart sample. This is a prerequisite for running the quickstart. ```bash $ cd shiro-root-3.0.0/samples/quickstart ``` -------------------------------- ### PropertiesRealm Example Configuration Source: https://shiro.apache.org/static/2.0.0/shiro-core/xref/org/apache/shiro/realm/text/PropertiesRealm.html This example demonstrates the format for defining user-to-role and role-to-permission mappings in a properties file for PropertiesRealm. ```properties user.root = rootPassword,administrator user.jsmith = jsmithPassword,manager,engineer,employee user.abrown = abrownPassword,qa,employee user.djones = djonesPassword,qa,contractor role.administrator = * role.manager = "user:read,write", file:execute:/usr/local/emailManagers.sh role.engineer = "file:read,execute:/usr/local/tomcat/bin/startup.sh" role.employee = application:use:wiki role.qa = "server:view,start,shutdown,restart:someQaServer", server:view:someProductionServer role.contractor = application:use:timesheet ``` -------------------------------- ### Run Shiro Quickstart with Maven Source: https://shiro.apache.org/10-minute-tutorial.html Compiles and runs the Shiro quickstart application using Maven. This will print log messages indicating the progress. ```bash $ mvn compile exec:java ``` -------------------------------- ### Shiro Filter Chain Configuration Example Source: https://shiro.apache.org/static/current/apidocs/shiro-web/org/apache/shiro/web/filter/authz/HttpMethodPermissionFilter.html Example of configuring the HttpMethodPermissionFilter in a Shiro filter chain. This setup applies the 'rest' filter to paths starting with '/user/**', enabling method-based permission checks. ```java /user/** = rest[user] ``` -------------------------------- ### Shiro Spring Quickstart Demonstration Source: https://shiro.apache.org/static/2.0.0/shiro-samples/samples-spring/xref/org/apache/shiro/samples/spring/QuickStart.html This code demonstrates a typical Shiro workflow: obtaining the subject, logging in, checking roles and permissions, interacting with services, and logging out. It requires a configured SecurityManager and a SimpleService. ```java Subject subject = SecurityUtils.getSubject(); // Subject is not authenticated yet Assert.isTrue(!subject.isAuthenticated()); // login the subject with a username / password UsernamePasswordToken token = new UsernamePasswordToken("joe.coder", "password"); subject.login(token); // joe.coder has the "user" role subject.checkRole("user"); // joe.coder does NOT have the admin role Assert.isTrue(!subject.hasRole("admin")); // joe.coder has the "read" permission subject.checkPermission("read"); // current user is allowed to execute this method. simpleService.readRestrictedCall(); try { // but not this one! simpleService.writeRestrictedCall(); } catch (AuthorizationException e) { log.info("Subject was NOT allowed to execute method 'writeRestrictedCall'"); } // logout subject.logout(); Assert.isTrue(!subject.isAuthenticated()); ``` -------------------------------- ### Example [main] Section Configuration Source: https://shiro.apache.org/configuration.html Configures the SecurityManager and its dependencies within the [main] section. Demonstrates setting credentials matchers, realms, and session timeouts using a 'poor man's' Dependency Injection approach. ```ini [main] sha256Matcher = org.apache.shiro.authc.credential.Sha256CredentialsMatcher myRealm = com.company.security.shiro.DatabaseRealm myRealm.connectionTimeout = 30000 myRealm.username = jsmith myRealm.password = secret myRealm.credentialsMatcher = $sha256Matcher securityManager.sessionManager.globalSessionTimeout = 1800000 ``` -------------------------------- ### Configure Shiro SecurityManager with CDI Source: https://shiro.apache.org/jakarta-ee.html Example of configuring Shiro's SecurityManager using CDI without a shiro.ini file. This setup is suitable for environments that primarily use CDI for dependency injection. ```java @ApplicationScoped public class MyBean { private DefaultSecurityManager securityManager; void configureSecurityManager(@Observes @Initialized(ApplicationScoped.class) Object nothing) { var realm = new SimpleAccountRealm(); securityManager = new DefaultSecurityManager(realm); realm.addAccount("powerful", "awesome", "admin"); realm.addAccount("regular", "meh", "user"); SecurityUtils.setSecurityManager(securityManager); } void destroySecurityManager(@Observes @Destroyed(ApplicationScoped.class) Object nothing) { securityManager.destroy(); SecurityUtils.setSecurityManager(null); } } ``` -------------------------------- ### Unauthorized URL Configuration Source: https://shiro.apache.org/static/2.0.0/shiro-support/shiro-spring/xref/org/apache/shiro/spring/web/ShiroFilterFactoryBean.html Provides methods to get and set the application's 'unauthorized' URL. This URL is applied globally to Shiro filters that subclass AuthorizationFilter, simplifying configuration by avoiding manual setup on each filter. Explicitly configured filters will retain their settings. ```APIDOC ## getUnauthorizedUrl ### Description Returns the application's 'unauthorized' URL to be assigned to all acquired Filters that subclass AuthorizationFilter or null if no value should be assigned globally. The default value is null. ### Method GET ### Endpoint N/A (Java Method) ### Parameters None ### Response #### Success Response - **unauthorizedUrl** (String) - The application's unauthorized URL. ## setUnauthorizedUrl ### Description Sets the application's 'unauthorized' URL to be assigned to all acquired Filters that subclass AuthorizationFilter. This convenience mechanism passes the value to each Filter via the AuthorizationFilter.setUnauthorizedUrl(String) method. Individual filter configurations will override this global property. ### Method POST ### Endpoint N/A (Java Method) ### Parameters - **unauthorizedUrl** (String) - Required - The application's unauthorized URL to apply as a convenience to all discovered AuthorizationFilter instances. ### Request Example ```json { "unauthorizedUrl": "/unauthorized" } ``` ### Response #### Success Response Void ``` -------------------------------- ### Success URL Configuration Source: https://shiro.apache.org/static/2.0.0/shiro-support/shiro-spring/xref/org/apache/shiro/spring/web/ShiroFilterFactoryBean.html Provides methods to get and set the application's after-login success URL. This URL is applied globally to Shiro filters that subclass AuthenticationFilter, simplifying configuration by avoiding manual setup on each filter. Explicitly configured filters will retain their settings. ```APIDOC ## getSuccessUrl ### Description Returns the application's after-login success URL to be assigned to all acquired Filters that subclass AuthenticationFilter or null if no value should be assigned globally. The default value is null. ### Method GET ### Endpoint N/A (Java Method) ### Parameters None ### Response #### Success Response - **successUrl** (String) - The application's after-login success URL. ## setSuccessUrl ### Description Sets the application's after-login success URL to be assigned to all acquired Filters that subclass AuthenticationFilter. This convenience mechanism passes the value to each Filter via the AuthenticationFilter.setSuccessUrl(String) method. Individual filter configurations will override this global property. ### Method POST ### Endpoint N/A (Java Method) ### Parameters - **successUrl** (String) - Required - The application's after-login success URL to apply as a convenience to all discovered AuthenticationFilter instances. ### Request Example ```json { "successUrl": "/loginSuccess" } ``` ### Response #### Success Response Void ``` -------------------------------- ### Example Hashed Password Output Source: https://shiro.apache.org/v2/command-line-hasher.html This is an example of the securely-salted-iterated-and-hashed password output generated by the hasher. ```text [INFO ] $shiro2$argon2id$v=19$t=1,m=65536,p=4$H5z81Jpr4ntZr3MVtbOUBw$fJDgZCLZjMC6A2HhnSpxULMmvVdW3su+/GCU3YbxfFQ ``` -------------------------------- ### Checkout Tutorial Branch Source: https://shiro.apache.org/webapp-tutorial.html Use this command to switch to the 'step6' branch of the tutorial project to follow along with the RBAC steps. ```bash $ git checkout step6 ``` -------------------------------- ### Examples of Resource Hashing Commands Source: https://shiro.apache.org/v2/command-line-hasher.html Illustrates various ways to specify resource paths for hashing, including relative, absolute, URL, and classpath resources. ```bash -r fileInCurrentDirectory.txt ``` ```bash -r ../../relativePathFile.xml ``` ```bash -r ~/documents/myfile.pdf ``` ```bash -r /usr/local/logs/absolutePathFile.log ``` ```bash -r url:http://foo.com/page.html ``` ```bash -r classpath:/WEB-INF/lib/something.jar ``` -------------------------------- ### Example Hashed Password Output Source: https://shiro.apache.org/command-line-hasher.html This is an example of the output format for a securely hashed password generated by the Shiro hasher. ```text $shiro1$SHA-256$500000$eWpVX2tGX7WCP2J+jMCNqw==$it/NRclMOHrfOvhAEFZ0mxIZRdbcfqIBdwdwdDXW2dM= ``` -------------------------------- ### Run the Web Application Source: https://shiro.apache.org/webapp-tutorial.html Start the Apache Shiro tutorial web application using the Maven Jetty plugin. Access the application by navigating to http://localhost:8080 in your web browser. ```bash $ mvn jetty:run ``` -------------------------------- ### Examples of Hashing Different Resource Types Source: https://shiro.apache.org/command-line-hasher.html Demonstrates how to hash files using relative or absolute paths, and how to specify different algorithms like SHA-512. ```bash -r fileInCurrentDirectory.txt ``` ```bash -r ../../relativePathFile.xml ``` ```bash -r ~/documents/myfile.pdf ``` ```bash -r ~/documents/myfile.pdf -a SHA-512 ``` ```bash -r /usr/local/logs/absolutePathFile.log ``` ```bash -r url:http://foo.com/page.html ``` ```bash -r classpath:/WEB-INF/lib/something.jar ``` -------------------------------- ### Shiro Hasher Usage Example Source: https://shiro.apache.org/static/2.0.0/shiro-tools/shiro-tools-hasher/xref/org/apache/shiro/tools/hasher/Hasher.html To see all supported options and their documentation, run the Shiro Hasher tool without any arguments. This will print the help message to the console. ```bash java -jar shiro-tools-hasher-version-cli.jar ``` -------------------------------- ### Shiro CDI Bean Example Source: https://shiro.apache.org/jakarta-ee.html Example of a CDI bean with `@Named` and `@ApplicationScoped` annotations, demonstrating how to expose bean properties for use in `shiro.ini`. ```java @Named @ApplicationScoped public class MyBean { public boolean getMyValue() { return true; } } ``` -------------------------------- ### Java Annotation Example Source: https://shiro.apache.org/static/current/apidocs/org/apache/shiro/authz/annotation/RequiresPermissions.html Example of using the RequiresPermissions annotation on a Java method. This method requires the Subject to have both 'file:read' and 'write:aFile.txt' permissions. ```java @RequiresPermissions( {"file:read", "write:aFile.txt"} ) void someMethod(); ``` -------------------------------- ### Gradle/Grails Dependency Source: https://shiro.apache.org/static/2.0.0/shiro-samples/samples-quickstart-guice/dependency-info.html Configure your Gradle or Grails build file to include the samples-quickstart-guice dependency. ```groovy implementation 'org.apache.shiro.samples:samples-quickstart-guice:2.0.0' ``` -------------------------------- ### Stormpath API Key Properties File Example Source: https://shiro.apache.org/webapp-tutorial.html This is an example of the content found in the apiKey.properties file generated by Stormpath. It contains your API key ID and secret. ```properties stormpath_api_key_id=YOUR_API_KEY_ID stormpath_api_key_secret=YOUR_API_KEY_SECRET ``` -------------------------------- ### Initialize Shiro SecurityManager with Guice Source: https://shiro.apache.org/static/2.0.0/shiro-samples/samples-quickstart-guice/xref/QuickstartGuice.html This snippet shows the standard Guice bootstrapping process to create and configure Shiro's SecurityManager. It's essential for setting up Shiro in a Guice-based application. ```java Injector injector = Guice.createInjector(new QuickstartShiroModule()); SecurityManager securityManager = injector.getInstance(SecurityManager.class); SecurityUtils.setSecurityManager(securityManager); ``` -------------------------------- ### Maven Dependency Source: https://shiro.apache.org/static/2.0.0/shiro-samples/samples-quickstart-guice/dependency-info.html Include this snippet in your Maven project's pom.xml to add the samples-quickstart-guice artifact. ```xml org.apache.shiro.samples samples-quickstart-guice 2.0.0 ``` -------------------------------- ### applicationContext.xml Servlet Filter Bean Example Source: https://shiro.apache.org/spring-xml.html Example of defining a standard javax.servlet.Filter bean in Spring XML. Such beans are automatically discovered by the 'shiroFilter' and can be referenced in 'filterChainDefinitions'. ```xml ... ``` -------------------------------- ### Clone Tutorial Repository Source: https://shiro.apache.org/webapp-tutorial.html Clone the Apache Shiro tutorial webapp from GitHub to your local machine. Replace `$YOUR_GITHUB_USERNAME` with your actual GitHub username. ```bash $ git clone git@github.com:$YOUR_GITHUB_USERNAME/apache-shiro-tutorial-webapp.git ``` -------------------------------- ### Instance-Level Access Control Examples Source: https://shiro.apache.org/permissions.html Examples of defining instance-level access control using wildcard permissions. These permissions specify a domain, an action, and a specific instance. ```plaintext printer:query:lp7200 printer:print:epsoncolor ``` ```plaintext printer:print:* ``` ```plaintext printer:*:* ``` ```plaintext printer:*:lp7200 ``` ```plaintext printer:query,print:lp7200 ``` -------------------------------- ### Framework INI Configuration Example Source: https://shiro.apache.org/static/2.0.0/shiro-web/xref/org/apache/shiro/web/env/IniWebEnvironment.html An extension point for subclasses to provide INI configuration that will be merged into the user's configuration. User configuration takes precedence. ```java protected Ini getFrameworkIni() { return null; } ``` -------------------------------- ### Get Servlet Context Resource Stream Source: https://shiro.apache.org/static/2.0.0/shiro-web/xref/org/apache/shiro/web/env/IniWebEnvironment.html Retrieves an InputStream for a resource within the ServletContext. It normalizes the path and checks if the ServletContext is available before attempting to get the resource. ```java private InputStream getServletContextResourceStream(String path) { InputStream is = null; path = WebUtils.normalize(path); ServletContext sc = getServletContext(); if (sc != null) { is = sc.getResourceAsStream(path); } return is; } ``` -------------------------------- ### Constructor Details Source: https://shiro.apache.org/static/current/apidocs/org/apache/shiro/realm/AuthenticatingRealm.html Details on how to construct an AuthenticatingRealm instance, with options for providing a CacheManager and a CredentialsMatcher. ```APIDOC ## Constructor Details ### AuthenticatingRealm public AuthenticatingRealm() ### AuthenticatingRealm public AuthenticatingRealm(org.apache.shiro.cache.CacheManager cacheManager) ### AuthenticatingRealm public AuthenticatingRealm(CredentialsMatcher matcher) ### AuthenticatingRealm public AuthenticatingRealm(org.apache.shiro.cache.CacheManager cacheManager, CredentialsMatcher matcher) ``` -------------------------------- ### RequiresRoles Annotation Example Source: https://shiro.apache.org/static/current/apidocs/org/apache/shiro/authz/annotation/RequiresRoles.html This example shows how to use the @RequiresRoles annotation to restrict method execution to users with a specific role. If the subject does not have the 'aRoleName' role, the method will not execute. ```java @RequiresRoles("aRoleName") void someMethod(); ``` -------------------------------- ### JndiTemplate doInContext Example Source: https://shiro.apache.org/static/2.0.0/shiro-core/xref/org/apache/shiro/jndi/JndiTemplate.html Demonstrates the doInContext method of JndiTemplate, which is used to perform JNDI operations within a given context. This specific example shows unbinding a name from the context. ```java public Object doInContext(Context ctx) throws NamingException { ctx.unbind(name); return null; } ``` -------------------------------- ### Navigate to Project Directory Source: https://shiro.apache.org/webapp-tutorial.html Change the current directory to the root of the cloned Apache Shiro tutorial webapp project. ```bash $ cd apache-shiro-tutorial-webapp ``` -------------------------------- ### Example shiro.ini [urls] section Source: https://shiro.apache.org/web.html This snippet shows a sample [urls] section in shiro.ini, demonstrating how to map URL paths to filter chains. ```ini # [main], [users] and [roles] above here ... [urls] ... ``` -------------------------------- ### Get Subject from ThreadContext Source: https://shiro.apache.org/static/2.0.0/shiro-core/xref/org/apache/shiro/util/ThreadContext.html Retrieves the Subject instance bound to the current thread's context without removing it. Returns null if no Subject is bound. This is a convenience wrapper for the get operation. ```java return (Subject) get(SUBJECT_KEY); ``` -------------------------------- ### PMD Processing Error Example Source: https://shiro.apache.org/static/2.0.0/shiro-support/shiro-cdi/pmd.html This snippet shows an example of a PMD processing error, specifically an issue with parsing a Java file due to method reference usage in an older JDK version. ```text Filename | Problem ---|--- org/apache/shiro/cdi/AnnotatedTypeWrapper.java | PMDException: Error while parsing /Users/lprimak/dev/shiro/support/cdi/src/main/java/org/apache/shiro/cdi/AnnotatedTypeWrapper.java ``` net.sourceforge.pmd.PMDException: Error while parsing /Users/lprimak/dev/shiro/support/cdi/src/main/java/org/apache/shiro/cdi/AnnotatedTypeWrapper.java at net.sourceforge.pmd.SourceCodeProcessor.processSourceCodeWithoutCache(SourceCodeProcessor.java:124) at net.sourceforge.pmd.SourceCodeProcessor.processSourceCode(SourceCodeProcessor.java:100) at net.sourceforge.pmd.SourceCodeProcessor.processSourceCode(SourceCodeProcessor.java:62) at net.sourceforge.pmd.processor.PmdRunnable.call(PmdRunnable.java:89) at net.sourceforge.pmd.processor.PmdRunnable.call(PmdRunnable.java:30) at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:317) at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:572) at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:317) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:642) at java.base/java.lang.Thread.run(Thread.java:1583) Caused by: net.sourceforge.pmd.lang.java.ast.ParseException: Line 50, Column 48: Cannot use method references when running in JDK inferior to 1.8 mode! at net.sourceforge.pmd.lang.java.ast.JavaParser.throwParseException(JavaParser.java:30) at net.sourceforge.pmd.lang.java.ast.JavaParser.checkForBadMethodReferenceUsage(JavaParser.java:118) at net.sourceforge.pmd.lang.java.ast.JavaParser.MethodReference(JavaParser.java:4796) at net.sourceforge.pmd.lang.java.ast.JavaParser.MemberSelector(JavaParser.java:4762) at net.sourceforge.pmd.lang.java.ast.JavaParser.PrimarySuffix(JavaParser.java:5256) at net.sourceforge.pmd.lang.java.ast.JavaParser.PrimaryExpression(JavaParser.java:4680) at net.sourceforge.pmd.lang.java.ast.JavaParser.PostfixExpression(JavaParser.java:4494) at net.sourceforge.pmd.lang.java.ast.JavaParser.UnaryExpressionNotPlusMinus(JavaParser.java:4392) at net.sourceforge.pmd.lang.java.ast.JavaParser.UnaryExpression(JavaParser.java:4269) at net.sourceforge.pmd.lang.java.ast.JavaParser.MultiplicativeExpression(JavaParser.java:4184) at net.sourceforge.pmd.lang.java.ast.JavaParser.AdditiveExpression(JavaParser.java:4131) at net.sourceforge.pmd.lang.java.ast.JavaParser.ShiftExpression(JavaParser.java:4074) at net.sourceforge.pmd.lang.java.ast.JavaParser.RelationalExpression(JavaParser.java:4013) at net.sourceforge.pmd.lang.java.ast.JavaParser.InstanceOfExpression(JavaParser.java:3941) at net.sourceforge.pmd.lang.java.ast.JavaParser.EqualityExpression(JavaParser.java:3686) at net.sourceforge.pmd.lang.java.ast.JavaParser.AndExpression(JavaParser.java:3646) at net.sourceforge.pmd.lang.java.ast.JavaParser.ExclusiveOrExpression(JavaParser.java:3606) at net.sourceforge.pmd.lang.java.ast.JavaParser.InclusiveOrExpression(JavaParser.java:3566) at net.sourceforge.pmd.lang.java.ast.JavaParser.ConditionalAndExpression(JavaParser.java:3526) at net.sourceforge.pmd.lang.java.ast.JavaParser.ConditionalOrExpression(JavaParser.java:3486) at net.sourceforge.pmd.lang.java.ast.JavaParser.ConditionalExpression(JavaParser.java:3448) at net.sourceforge.pmd.lang.java.ast.JavaParser.Expression(JavaParser.java:3307) at net.sourceforge.pmd.lang.java.ast.JavaParser.ArgumentList(JavaParser.java:5485) at net.sourceforge.pmd.lang.java.ast.JavaParser.Arguments(JavaParser.java:5451) at net.sourceforge.pmd.lang.java.ast.JavaParser.PrimarySuffix(JavaParser.java:5277) at net.sourceforge.pmd.lang.java.ast.JavaParser.PrimaryExpression(JavaParser.java:4680) at net.sourceforge.pmd.lang.java.ast.JavaParser.PostfixExpression(JavaParser.java:4494) at net.sourceforge.pmd.lang.java.ast.JavaParser.UnaryExpressionNotPlusMinus(JavaParser.java:4392) at net.sourceforge.pmd.lang.java.ast.JavaParser.UnaryExpression(JavaParser.java:4269) at net.sourceforge.pmd.lang.java.ast.JavaParser.MultiplicativeExpression(JavaParser.java:4184) at net.sourceforge.pmd.lang.java.ast.JavaParser.AdditiveExpression(JavaParser.java:4131) at net.sourceforge.pmd.lang.java.ast.JavaParser.ShiftExpression(JavaParser.java:4074) at net.sourceforge.pmd.lang.java.ast.JavaParser.RelationalExpression(JavaParser.java:4013) at net.sourceforge.pmd.lang.java.ast.JavaParser.InstanceOfExpression(JavaParser.java:3941) at net.sourceforge.pmd.lang.java.ast.JavaParser.EqualityExpression(JavaParser.java:3686) ``` -------------------------------- ### Checkout Step 5 Branch Source: https://shiro.apache.org/webapp-tutorial.html Use this command to switch to the 'step5' branch of the project to apply the tutorial changes. ```bash $ git checkout step5 ``` -------------------------------- ### Maven Dependency Source: https://shiro.apache.org/static/2.0.0/shiro-samples/samples-quickstart/dependency-info.html Use this snippet to add the Shiro Samples Quickstart as a dependency in your Apache Maven project. ```xml org.apache.shiro.samples samples-quickstart 2.0.0 ``` -------------------------------- ### EHCache Session Cache Configuration Example Source: https://shiro.apache.org/session-management.html This is an example of an EHCache configuration for Shiro's active sessions. Ensure 'overflowToDisk' is true and 'eternal' is true for proper session handling. You can adjust 'maxElementsInMemory' as needed. ```xml ``` -------------------------------- ### Start Session and Store ID Source: https://shiro.apache.org/static/2.0.0/shiro-web/xref/org/apache/shiro/web/session/mgt/DefaultWebSessionManager.html Called when a new session is started. If session ID cookies are enabled, it stores the session ID in a cookie. It also removes the referenced session ID source and marks the session as new. ```java @Override protected void onStart(Session session, SessionContext context) { super.onStart(session, context); if (!WebUtils.isHttp(context)) { LOGGER.debug("SessionContext argument is not HTTP compatible or does not have an HTTP request/response " + "pair. No session ID cookie will be set."); return; } HttpServletRequest request = WebUtils.getHttpRequest(context); HttpServletResponse response = WebUtils.getHttpResponse(context); if (isSessionIdCookieEnabled()) { Serializable sessionId = session.getId(); storeSessionId(sessionId, request, response); } else { LOGGER.debug("Session ID cookie is disabled. No cookie has been set for new session with id {}", session.getId()); } request.removeAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE); request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_IS_NEW, Boolean.TRUE); } ``` -------------------------------- ### Wildcard Permission Example Source: https://shiro.apache.org/permissions.html Demonstrates a wildcard permission string that implies the ability to perform a specific action. ```text user:* ``` -------------------------------- ### Checkout Step 2 Branch Source: https://shiro.apache.org/webapp-tutorial.html Use this command to switch to the 'step2' branch of the project, which contains the initial setup for Shiro integration. ```bash $ git checkout step2 ``` -------------------------------- ### getPathTraversalBlockMode Source: https://shiro.apache.org/static/current/apidocs/shiro-web/org/apache/shiro/web/filter/InvalidRequestFilter.html Gets the path traversal block mode. ```APIDOC ### getPathTraversalBlockMode public InvalidRequestFilter.PathTraversalBlockMode getPathTraversalBlockMode() ``` -------------------------------- ### Checkout Step 1 Branch Source: https://shiro.apache.org/webapp-tutorial.html Use this command to switch to the branch containing the initial Shiro configuration. ```bash $ git checkout step1 ``` -------------------------------- ### getChainNames Source: https://shiro.apache.org/static/2.0.0/shiro-web/xref/org/apache/shiro/web/filter/mgt/DefaultFilterChainManager.html Gets the names of all configured filter chains. ```APIDOC ## getChainNames ### Description Returns a set of names for all filter chains currently managed. ### Method public Set getChainNames() ### Return Value - **Set** - A set containing the names of all configured filter chains. ``` -------------------------------- ### Get Password Source: https://shiro.apache.org/static/2.0.0/shiro-web/xref/org/apache/shiro/web/filter/authc/FormAuthenticationFilter.html Retrieves the password parameter from the request. ```java protected String getPassword(ServletRequest request) { return WebUtils.getCleanParam(request, getPasswordParam()); } ``` -------------------------------- ### Example of URL Path Expression Matching Source: https://shiro.apache.org/web.html Demonstrates how an Ant-style path expression like '/account/**' matches requests to '/account' and its sub-paths. ```ini /account/** = ssl, authc ``` -------------------------------- ### Setup Filter Chain Configurations Source: https://shiro.apache.org/static/2.0.0/shiro-support/shiro-guice/xref/org/apache/shiro/guice/web/ShiroWebModule.html Prepares the filter chain configurations by merging global filters with path-specific filters. It builds maps required for the FilterChainResolver. ```java private Map[]> setupFilterChainConfigs() { // loop through and build a map of Filter Key -> Map Map, Map> filterToPathToConfig = new HashMap, Map>(); // At the same time build a map to return with Path -> Key[] Map[]> resultConfigMap = new LinkedHashMap[]>(); for (Map.Entry[]> filterChain : filterChains.entrySet()) { String path = filterChain.getKey(); // collect the keys used for this path List> keysForPath = new ArrayList>(); List> globalFilters = this.globalFilters(); FilterConfig[] pathFilters = filterChain.getValue(); // merge the global filters and the path specific filters List> filterConfigs = new ArrayList<>(globalFilters.size() + pathFilters.length); filterConfigs.addAll(globalFilters); filterConfigs.addAll(Arrays.asList(pathFilters)); ``` -------------------------------- ### Get Username Source: https://shiro.apache.org/static/2.0.0/shiro-web/xref/org/apache/shiro/web/filter/authc/FormAuthenticationFilter.html Retrieves the username parameter from the request. ```java protected String getUsername(ServletRequest request) { return WebUtils.getCleanParam(request, getUsernameParam()); } ``` -------------------------------- ### Order Matters: First Match Wins Example Source: https://shiro.apache.org/web.html Illustrates the 'first match wins' policy for URL path expressions, showing how the order of definitions affects matching. ```ini /account/** = ssl, authc /account/signup = anon ``` -------------------------------- ### getPasswordParam Source: https://shiro.apache.org/static/current/apidocs/shiro-web/org/apache/shiro/web/filter/authc/FormAuthenticationFilter.html Gets the request parameter name used for the password. ```APIDOC ## getPasswordParam() ### Description Gets the request parameter name used for the password. ### Method `String getPasswordParam()` ### Returns * **String** - The request parameter name for the password. ``` -------------------------------- ### Example shiro.ini User Entry Source: https://shiro.apache.org/v2/command-line-hasher.html This shows how to place the generated hashed password into a user definition line within the shiro.ini file. ```ini [users] ... user1 = "$shiro2$argon2id$v=19$t=1,m=65536,p=4$H5z81Jpr4ntZr3MVtbOUBw$fJDgZCLZjMC6A2HhnSpxULMmvVdW3su+/GCU3YbxfFQ" ``` -------------------------------- ### getUsernameParam Source: https://shiro.apache.org/static/current/apidocs/shiro-web/org/apache/shiro/web/filter/authc/FormAuthenticationFilter.html Gets the request parameter name used for the username. ```APIDOC ## getUsernameParam() ### Description Gets the request parameter name used for the username. ### Method `String getUsernameParam()` ### Returns * **String** - The request parameter name for the username. ``` -------------------------------- ### Shiro Initialization Log Output Source: https://shiro.apache.org/webapp-tutorial.html Example log output indicating successful Shiro environment initialization in the web application. ```log 16:08:25.466 [main] INFO o.a.shiro.web.env.EnvironmentLoader - Starting Shiro environment initialization. 16:08:26.201 [main] INFO o.a.s.c.IniSecurityManagerFactory - Realms have been explicitly set on the SecurityManager instance - auto-setting of realms will not occur. 16:08:26.201 [main] INFO o.a.shiro.web.env.EnvironmentLoader - Shiro environment initialized in 731 ms. ``` -------------------------------- ### getApplicationName Source: https://shiro.apache.org/static/current/apidocs/shiro-web/org/apache/shiro/web/filter/authc/BearerHttpAuthenticationFilter.html Gets the application name used in the WWW-Authenticate header. ```APIDOC ## getApplicationName() ### Description Returns the name to use in the ServletResponse's **`WWW-Authenticate`** header. Per RFC 2617, this name is displayed to the end user when they are asked to authenticate. Unless overridden by the `setApplicationName(String)` method, the default value is 'application'. ### Method `public String getApplicationName()` ### Returns the name to use in the ServletResponse's 'WWW-Authenticate' header. ``` -------------------------------- ### Groovy Grape Dependency Source: https://shiro.apache.org/static/2.0.0/shiro-samples/samples-quickstart/dependency-info.html Add the Shiro Samples Quickstart to your Groovy project using Groovy Grape. ```groovy @Grapes( @Grab(group='org.apache.shiro.samples', module='samples-quickstart', version='2.0.0') ) ``` -------------------------------- ### Get ServletResponse from WebSessionKey Source: https://shiro.apache.org/static/2.0.0/shiro-web/xref/org/apache/shiro/web/session/mgt/WebSessionKey.html Retrieves the ServletResponse associated with this WebSessionKey. ```java public ServletResponse getServletResponse() { return servletResponse; } ```