001    /*
002     * Licensed to the Apache Software Foundation (ASF) under one
003     * or more contributor license agreements.  See the NOTICE file
004     * distributed with this work for additional information
005     * regarding copyright ownership.  The ASF licenses this file
006     * to you under the Apache License, Version 2.0 (the
007     * "License"); you may not use this file except in compliance
008     * with the License.  You may obtain a copy of the License at
009     *
010     *     http://www.apache.org/licenses/LICENSE-2.0
011     *
012     * Unless required by applicable law or agreed to in writing,
013     * software distributed under the License is distributed on an
014     * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015     * KIND, either express or implied.  See the License for the
016     * specific language governing permissions and limitations
017     * under the License.
018     */
019    package org.apache.shiro;
020    
021    import org.apache.shiro.mgt.SecurityManager;
022    import org.apache.shiro.subject.Subject;
023    import org.apache.shiro.util.ThreadContext;
024    
025    
026    /**
027     * Accesses the currently accessible {@code Subject} for the calling code depending on runtime environment.
028     *
029     * @author Les Hazlewood
030     * @since 0.2
031     */
032    public abstract class SecurityUtils {
033    
034        /**
035         * ONLY used as a 'backup' in VM Singleton environments (that is, standalone environments), since the
036         * ThreadContext should always be the primary source for Subject instances when possible.
037         */
038        private static SecurityManager securityManager;
039    
040        /**
041         * Returns the currently accessible {@code Subject} available to the calling code depending on
042         * runtime environment.
043         * <p/>
044         * This method is provided as a way of obtaining a {@code Subject} without having to resort to
045         * implementation-specific methods.  It also allows the Shiro team to change the underlying implementation of
046         * this method in the future depending on requirements/updates without affecting your code that uses it.
047         *
048         * @return the currently accessible {@code Subject} accessible to the calling code.
049         * @throws IllegalStateException if no {@link Subject Subject} instance or
050         *                               {@link SecurityManager SecurityManager} instance is available with which to obtain
051         *                               a {@code Subject}, which which is considered an invalid application configuration
052         *                               - a Subject should <em>always</em> be available to the caller.
053         */
054        public static Subject getSubject() {
055            Subject subject = ThreadContext.getSubject();
056            if (subject == null) {
057                subject = (new Subject.Builder()).buildSubject();
058                ThreadContext.bind(subject);
059            }
060            return subject;
061        }
062    
063        /**
064         * Sets a VM (static) singleton SecurityManager, specifically for transparent use in the
065         * {@link #getSubject() getSubject()} implementation.
066         * <p/>
067         * <b>This method call exists mainly for framework development support.  Application developers should rarely,
068         * if ever, need to call this method.</b>
069         * <p/>
070         * The Shiro development team prefers that SecurityManager instances are non-static application singletons
071         * and <em>not</em> VM static singletons.  Application singletons that do not use static memory require some sort
072         * of application configuration framework to maintain the application-wide SecurityManager instance for you
073         * (for example, Spring or EJB3 environments) such that the object reference does not need to be static.
074         * <p/>
075         * In these environments, Shiro acquires Subject data based on the currently executing Thread via its own
076         * framework integration code, and this is the preferred way to use Shiro.
077         * <p/>
078         * However in some environments, such as a standalone desktop application or Applets that do not use Spring or
079         * EJB or similar config frameworks, a VM-singleton might make more sense (although the former is still preferred).
080         * In these environments, setting the SecurityManager via this method will automatically enable the
081         * {@link #getSubject() getSubject()} call to function with little configuration.
082         * <p/>
083         * For example, in these environments, this will work:
084         * <pre>
085         * DefaultSecurityManager securityManager = new {@link org.apache.shiro.mgt.DefaultSecurityManager DefaultSecurityManager}();
086         * securityManager.setRealms( ... ); //one or more Realms
087         * <b>SecurityUtils.setSecurityManager( securityManager );</b></pre>
088         * <p/>
089         * And then anywhere in the application code, the following call will return the application's Subject:
090         * <pre>
091         * Subject currentUser = SecurityUtils.getSubject();</pre>
092         *
093         * @param securityManager the securityManager instance to set as a VM static singleton.
094         */
095        public static void setSecurityManager(SecurityManager securityManager) {
096            SecurityUtils.securityManager = securityManager;
097        }
098    
099        /**
100         * Returns the SecurityManager accessible to the calling code.
101         * <p/>
102         * This implementation favors acquiring a thread-bound {@code SecurityManager} if it can find one.  If one is
103         * not available to the executing thread, it will attempt to use the static singleton if available (see the
104         * {@link #setSecurityManager setSecurityManager} method for more on the static singleton).
105         * <p/>
106         * If neither the thread-local or static singleton instances are available, this method throws an
107         * {@code UnavailableSecurityManagerException} to indicate an error - a SecurityManager should always be accessible
108         * to calling code in an application. If it is not, it is likely due to a Shiro configuration problem.
109         *
110         * @return the SecurityManager accessible to the calling code.
111         * @throws UnavailableSecurityManagerException
112         *          if there is no {@code SecurityManager} instance available to the
113         *          calling code, which typically indicates an invalid application configuration.
114         */
115        public static SecurityManager getSecurityManager() throws UnavailableSecurityManagerException {
116            SecurityManager securityManager = ThreadContext.getSecurityManager();
117            if (securityManager == null) {
118                securityManager = SecurityUtils.securityManager;
119            }
120            if (securityManager == null) {
121                String msg = "No SecurityManager accessible to the calling code, either bound to the " +
122                        ThreadContext.class.getName() + " or as a vm static singleton.  This is an invalid application " +
123                        "configuration.";
124                throw new UnavailableSecurityManagerException(msg);
125            }
126            return securityManager;
127        }
128    }