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.authc.pam;
020    
021    import org.apache.shiro.authc.*;
022    import org.apache.shiro.realm.Realm;
023    import org.apache.shiro.subject.PrincipalCollection;
024    import org.slf4j.Logger;
025    import org.slf4j.LoggerFactory;
026    
027    import java.util.Collection;
028    
029    /**
030     * A {@code ModularRealmAuthenticator} delgates account lookups to a pluggable (modular) collection of
031     * {@link Realm}s.  This enables PAM (Pluggable Authentication Module) behavior in Shiro.
032     * In addition to authorization duties, a Shiro Realm can also be thought of a PAM 'module'.
033     * <p/>
034     * Using this Authenticator allows you to &quot;plug-in&quot; your own
035     * {@code Realm}s as you see fit.  Common realms are those based on accessing
036     * LDAP, relational databases, file systems, etc.
037     * <p/>
038     * If only one realm is configured (this is often the case for most applications), authentication success is naturally
039     * only dependent upon invoking this one Realm's
040     * {@link Realm#getAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)} method.
041     * <p/>
042     * But if two or more realms are configured, PAM behavior is implemented by iterating over the collection of realms
043     * and interacting with each over the course of the authentication attempt.  As this is more complicated, this
044     * authenticator allows customized behavior for interpreting what happens when interacting with multiple realms - for
045     * example, you might require all realms to be successful during the attempt, or perhaps only at least one must be
046     * successful, or some other interpretation.  This customized behavior can be performed via the use of a
047     * {@link #setAuthenticationStrategy(AuthenticationStrategy) AuthenticationStrategy}, which
048     * you can inject as a property of this class.
049     * <p/>
050     * The strategy object provides callback methods that allow you to
051     * determine what constitutes a success or failure in a multi-realm (PAM) scenario.  And because this only makes sense
052     * in a mult-realm scenario, the strategy object is only utilized when more than one Realm is configured.
053     * <p/>
054     * As most multi-realm applications require at least one Realm authenticates successfully, the default
055     * implementation is the {@link AtLeastOneSuccessfulStrategy}.
056     *
057     * @author Jeremy Haile
058     * @author Les Hazlewood
059     * @see #setRealms
060     * @see AtLeastOneSuccessfulStrategy
061     * @see AllSuccessfulStrategy
062     * @see FirstSuccessfulStrategy
063     * @since 0.1
064     */
065    public class ModularRealmAuthenticator extends AbstractAuthenticator {
066    
067        /*--------------------------------------------
068        |             C O N S T A N T S             |
069        ============================================*/
070        private static final Logger log = LoggerFactory.getLogger(ModularRealmAuthenticator.class);
071    
072        /*--------------------------------------------
073        |    I N S T A N C E   V A R I A B L E S    |
074        ============================================*/
075        /**
076         * List of realms that will be iterated through when a user authenticates.
077         */
078        private Collection<Realm> realms;
079    
080        /**
081         * The authentication strategy to use during authentication attempts, defaults to a
082         * {@link org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy} instance.
083         */
084        private AuthenticationStrategy authenticationStrategy;
085    
086        /*--------------------------------------------
087        |         C O N S T R U C T O R S           |
088        ============================================*/
089    
090        /**
091         * Default no-argument constructor which
092         * {@link #setAuthenticationStrategy(AuthenticationStrategy) enables}  an
093         * {@link org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy} by default.
094         */
095        public ModularRealmAuthenticator() {
096            this.authenticationStrategy = new AtLeastOneSuccessfulStrategy();
097        }
098    
099        /*--------------------------------------------
100        |  A C C E S S O R S / M O D I F I E R S    |
101        ============================================*/
102    
103        /**
104         * Sets all realms used by this Authenticator, providing PAM (Pluggable Authentication Module) configuration.
105         *
106         * @param realms the realms to consult during authentication attempts.
107         */
108        public void setRealms(Collection<Realm> realms) {
109            this.realms = realms;
110        }
111    
112        /**
113         * Returns the realm(s) used by this {@code Authenticator} during an authentication attempt.
114         *
115         * @return the realm(s) used by this {@code Authenticator} during an authentication attempt.
116         */
117        protected Collection<Realm> getRealms() {
118            return this.realms;
119        }
120    
121        /**
122         * Returns the {@code AuthenticationStrategy} utilized by this modular authenticator during a multi-realm
123         * log-in attempt.  This object is only used when two or more Realms are configured.
124         * <p/>
125         * Unless overridden by
126         * the {@link #setAuthenticationStrategy(AuthenticationStrategy)} method, the default implementation
127         * is the {@link org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy}.
128         *
129         * @return the {@code AuthenticationStrategy} utilized by this modular authenticator during a log-in attempt.
130         * @since 0.2
131         */
132        public AuthenticationStrategy getAuthenticationStrategy() {
133            return authenticationStrategy;
134        }
135    
136        /**
137         * Allows overriding the default {@code AuthenticationStrategy} utilized during multi-realm log-in attempts.
138         * This object is only used when two or more Realms are configured.
139         *
140         * @param authenticationStrategy the strategy implementation to use during log-in attempts.
141         * @since 0.2
142         */
143        public void setAuthenticationStrategy(AuthenticationStrategy authenticationStrategy) {
144            this.authenticationStrategy = authenticationStrategy;
145        }
146    
147        /*--------------------------------------------
148        |               M E T H O D S               |
149    
150        /**
151         * Used by the internal {@link #doAuthenticate} implementation to ensure that the {@code realms} property
152         * has been set.  The default implementation ensures the property is not null and not empty.
153         *
154         * @throws IllegalStateException if the {@code realms} property is configured incorrectly.
155         */
156    
157        protected void assertRealmsConfigured() throws IllegalStateException {
158            Collection<Realm> realms = getRealms();
159            if (realms == null || realms.isEmpty()) {
160                String msg = "Configuration error:  No realms have been configured!  One or more realms must be " +
161                        "present to execute an authentication attempt.";
162                throw new IllegalStateException(msg);
163            }
164        }
165    
166        /**
167         * Performs the authentication attempt by interacting with the single configured realm, which is significantly
168         * simpler than performing multi-realm logic.
169         *
170         * @param realm the realm to consult for AuthenticationInfo.
171         * @param token the submitted AuthenticationToken representing the subject's (user's) log-in principals and credentials.
172         * @return the AuthenticationInfo associated with the user account corresponding to the specified {@code token}
173         */
174        protected AuthenticationInfo doSingleRealmAuthentication(Realm realm, AuthenticationToken token) {
175            if (!realm.supports(token)) {
176                String msg = "Realm [" + realm + "] does not support authentication token [" +
177                        token + "].  Please ensure that the appropriate Realm implementation is " +
178                        "configured correctly or that the realm accepts AuthenticationTokens of this type.";
179                throw new UnsupportedTokenException(msg);
180            }
181            AuthenticationInfo info = realm.getAuthenticationInfo(token);
182            if (info == null) {
183                String msg = "Realm [" + realm + "] was unable to find account data for the " +
184                        "submitted AuthenticationToken [" + token + "].";
185                throw new UnknownAccountException(msg);
186            }
187            return info;
188        }
189    
190        /**
191         * Performs the multi-realm authentication attempt by calling back to a {@link AuthenticationStrategy} object
192         * as each realm is consulted for {@code AuthenticationInfo} for the specified {@code token}.
193         *
194         * @param realms the multiple realms configured on this Authenticator instance.
195         * @param token  the submitted AuthenticationToken representing the subject's (user's) log-in principals and credentials.
196         * @return an aggregated AuthenticationInfo instance representing account data across all the successfully
197         *         consulted realms.
198         */
199        protected AuthenticationInfo doMultiRealmAuthentication(Collection<Realm> realms, AuthenticationToken token) {
200    
201            AuthenticationStrategy strategy = getAuthenticationStrategy();
202    
203            AuthenticationInfo aggregate = strategy.beforeAllAttempts(realms, token);
204    
205            if (log.isTraceEnabled()) {
206                log.trace("Iterating through {} realms for PAM authentication", realms.size());
207            }
208    
209            for (Realm realm : realms) {
210    
211                if (realm.supports(token)) {
212    
213                    log.trace("Attempting to authenticate token [{}] using realm [{}]", token, realm);
214    
215                    AuthenticationInfo info = null;
216                    Throwable t = null;
217                    try {
218                        info = realm.getAuthenticationInfo(token);
219                    } catch (Throwable throwable) {
220                        t = throwable;
221                        if (log.isDebugEnabled()) {
222                            String msg = "Realm [" + realm + "] threw an exception during a multi-realm authentication attempt:";
223                            log.debug(msg, t);
224                        }
225                    }
226    
227                    aggregate = strategy.afterAttempt(realm, token, info, aggregate, t);
228    
229                } else {
230                    log.debug("Realm [{}] does not support token {}.  Skipping realm.", realm, token);
231                }
232            }
233    
234            aggregate = strategy.afterAllAttempts(token, aggregate);
235    
236            return aggregate;
237        }
238    
239    
240        /**
241         * Attempts to authenticate the given token by iterating over the internal collection of
242         * {@link Realm}s.  For each realm, first the {@link Realm#supports(org.apache.shiro.authc.AuthenticationToken)}
243         * method will be called to determine if the realm supports the {@code authenticationToken} method argument.
244         * <p/>
245         * If a realm does support
246         * the token, its {@link Realm#getAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)}
247         * method will be called.  If the realm returns a non-null account, the token will be
248         * considered authenticated for that realm and the account data recorded.  If the realm returns {@code null},
249         * the next realm will be consulted.  If no realms support the token or all supporting realms return null,
250         * an {@link AuthenticationException} will be thrown to indicate that the user could not be authenticated.
251         * <p/>
252         * After all realms have been consulted, the information from each realm is aggregated into a single
253         * {@link AuthenticationInfo} object and returned.
254         *
255         * @param authenticationToken the token containing the authentication principal and credentials for the
256         *                            user being authenticated.
257         * @return account information attributed to the authenticated user.
258         * @throws IllegalStateException   if no realms have been configured at the time this method is invoked
259         * @throws AuthenticationException if the user could not be authenticated or the user is denied authentication
260         *                                 for the given principal and credentials.
261         */
262        protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
263            assertRealmsConfigured();
264            Collection<Realm> realms = getRealms();
265            if (realms.size() == 1) {
266                return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken);
267            } else {
268                return doMultiRealmAuthentication(realms, authenticationToken);
269            }
270        }
271    
272        /**
273         * First calls <code>super.onLogout(principals)</code> to ensure a logout notification is issued, and for each
274         * wrapped {@code Realm} that implements the {@link LogoutAware LogoutAware} interface, calls
275         * <code>((LogoutAware)realm).onLogout(principals)</code> to allow each realm the opportunity to perform
276         * logout/cleanup operations during an user-logout.
277         * <p/>
278         * Shiro's Realm implementations all implement the {@code LogoutAware} interface by default and can be
279         * overridden for realm-specific logout logic.
280         *
281         * @param principals the application-specific Subject/user identifier.
282         */
283        public void onLogout(PrincipalCollection principals) {
284            super.onLogout(principals);
285            Collection<Realm> realms = getRealms();
286            if (realms != null && !realms.isEmpty()) {
287                for (Realm realm : realms) {
288                    if (realm instanceof LogoutAware) {
289                        ((LogoutAware) realm).onLogout(principals);
290                    }
291                }
292            }
293        }
294    }