1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one 3 * or more contributor license agreements. See the NOTICE file 4 * distributed with this work for additional information 5 * regarding copyright ownership. The ASF licenses this file 6 * to you under the Apache License, Version 2.0 (the 7 * "License"); you may not use this file except in compliance 8 * with the License. You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, 13 * software distributed under the License is distributed on an 14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 * KIND, either express or implied. See the License for the 16 * specific language governing permissions and limitations 17 * under the License. 18 */ 19 package org.apache.shiro.authc.pam; 20 21 import org.apache.shiro.authc.AbstractAuthenticator; 22 import org.apache.shiro.authc.AuthenticationException; 23 import org.apache.shiro.authc.AuthenticationInfo; 24 import org.apache.shiro.authc.AuthenticationToken; 25 import org.apache.shiro.authc.LogoutAware; 26 import org.apache.shiro.authc.UnknownAccountException; 27 import org.apache.shiro.realm.Realm; 28 import org.apache.shiro.subject.PrincipalCollection; 29 import org.apache.shiro.util.CollectionUtils; 30 import org.slf4j.Logger; 31 import org.slf4j.LoggerFactory; 32 33 import java.util.Collection; 34 35 /** 36 * A {@code ModularRealmAuthenticator} delegates account lookups to a pluggable (modular) collection of 37 * {@link Realm}s. This enables PAM (Pluggable Authentication Module) behavior in Shiro. 38 * In addition to authorization duties, a Shiro Realm can also be thought of a PAM 'module'. 39 * <p/> 40 * Using this Authenticator allows you to "plug-in" your own 41 * {@code Realm}s as you see fit. Common realms are those based on accessing 42 * LDAP, relational databases, file systems, etc. 43 * <p/> 44 * If only one realm is configured (this is often the case for most applications), authentication success is naturally 45 * only dependent upon invoking this one Realm's 46 * {@link Realm#getAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)} method. 47 * <p/> 48 * But if two or more realms are configured, PAM behavior is implemented by iterating over the collection of realms 49 * and interacting with each over the course of the authentication attempt. As this is more complicated, this 50 * authenticator allows customized behavior for interpreting what happens when interacting with multiple realms - for 51 * example, you might require all realms to be successful during the attempt, or perhaps only at least one must be 52 * successful, or some other interpretation. This customized behavior can be performed via the use of a 53 * {@link #setAuthenticationStrategy(AuthenticationStrategy) AuthenticationStrategy}, which 54 * you can inject as a property of this class. 55 * <p/> 56 * The strategy object provides callback methods that allow you to 57 * determine what constitutes a success or failure in a multi-realm (PAM) scenario. And because this only makes sense 58 * in a multi-realm scenario, the strategy object is only utilized when more than one Realm is configured. 59 * <p/> 60 * As most multi-realm applications require at least one Realm authenticates successfully, the default 61 * implementation is the {@link AtLeastOneSuccessfulStrategy}. 62 * 63 * @see #setRealms 64 * @see AtLeastOneSuccessfulStrategy 65 * @see AllSuccessfulStrategy 66 * @see FirstSuccessfulStrategy 67 * @since 0.1 68 */ 69 public class ModularRealmAuthenticator extends AbstractAuthenticator { 70 71 private static final Logger LOGGER = LoggerFactory.getLogger(ModularRealmAuthenticator.class); 72 73 /*-------------------------------------------- 74 | I N S T A N C E V A R I A B L E S | 75 ============================================*/ 76 /** 77 * List of realms that will be iterated through when a user authenticates. 78 */ 79 private Collection<Realm> realms; 80 81 /** 82 * The authentication strategy to use during authentication attempts, defaults to a 83 * {@link org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy} instance. 84 */ 85 private AuthenticationStrategy authenticationStrategy; 86 87 /*-------------------------------------------- 88 | C O N S T R U C T O R S | 89 ============================================*/ 90 91 /** 92 * Default no-argument constructor which 93 * {@link #setAuthenticationStrategy(AuthenticationStrategy) enables} an 94 * {@link org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy} by default. 95 */ 96 public ModularRealmAuthenticator() { 97 this.authenticationStrategy = new AtLeastOneSuccessfulStrategy(); 98 } 99 100 /*-------------------------------------------- 101 | A C C E S S O R S / M O D I F I E R S | 102 ============================================*/ 103 104 /** 105 * Sets all realms used by this Authenticator, providing PAM (Pluggable Authentication Module) configuration. 106 * 107 * @param realms the realms to consult during authentication attempts. 108 */ 109 public void setRealms(Collection<Realm> realms) { 110 this.realms = realms; 111 } 112 113 /** 114 * Returns the realm(s) used by this {@code Authenticator} during an authentication attempt. 115 * 116 * @return the realm(s) used by this {@code Authenticator} during an authentication attempt. 117 */ 118 protected Collection<Realm> getRealms() { 119 return this.realms; 120 } 121 122 /** 123 * Returns the {@code AuthenticationStrategy} utilized by this modular authenticator during a multi-realm 124 * log-in attempt. This object is only used when two or more Realms are configured. 125 * <p/> 126 * Unless overridden by 127 * the {@link #setAuthenticationStrategy(AuthenticationStrategy)} method, the default implementation 128 * is the {@link org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy}. 129 * 130 * @return the {@code AuthenticationStrategy} utilized by this modular authenticator during a log-in attempt. 131 * @since 0.2 132 */ 133 public AuthenticationStrategy getAuthenticationStrategy() { 134 return authenticationStrategy; 135 } 136 137 /** 138 * Allows overriding the default {@code AuthenticationStrategy} utilized during multi-realm log-in attempts. 139 * This object is only used when two or more Realms are configured. 140 * 141 * @param authenticationStrategy the strategy implementation to use during log-in attempts. 142 * @since 0.2 143 */ 144 public void setAuthenticationStrategy(AuthenticationStrategy authenticationStrategy) { 145 this.authenticationStrategy = authenticationStrategy; 146 } 147 148 /*-------------------------------------------- 149 | M E T H O D S | 150 151 /** 152 * Used by the internal {@link #doAuthenticate} implementation to ensure that the {@code realms} property 153 * has been set. The default implementation ensures the property is not null and not empty. 154 * 155 * @throws IllegalStateException if the {@code realms} property is configured incorrectly. 156 */ 157 158 protected void assertRealmsConfigured() throws IllegalStateException { 159 Collection<Realm> realms = getRealms(); 160 if (CollectionUtils.isEmpty(realms)) { 161 String msg = "Configuration error: No realms have been configured! One or more realms must be " 162 + "present to execute an authentication attempt."; 163 throw new IllegalStateException(msg); 164 } 165 } 166 167 /** 168 * Performs the authentication attempt by interacting with the single configured realm, which is significantly 169 * simpler than performing multi-realm logic. 170 * 171 * @param realm the realm to consult for AuthenticationInfo. 172 * @param token the submitted AuthenticationToken representing the subject's (user's) log-in principals and credentials. 173 * @return the AuthenticationInfo associated with the user account corresponding to the specified {@code token} 174 */ 175 protected AuthenticationInfo doSingleRealmAuthentication(Realm realm, AuthenticationToken token) { 176 if (!realm.supports(token)) { 177 String msg = "Realm [" + realm + "] does not support authentication token [" 178 + token + "]. Please ensure that the appropriate Realm implementation is " 179 + "configured correctly or that the realm accepts AuthenticationTokens of this type."; 180 throw new UnsupportedTokenException(msg); 181 } 182 AuthenticationInfo info = realm.getAuthenticationInfo(token); 183 if (info == null) { 184 String msg = "Realm [" + realm + "] was unable to find account data for the " 185 + "submitted AuthenticationToken [" + token + "]."; 186 throw new UnknownAccountException(msg); 187 } 188 return info; 189 } 190 191 /** 192 * Performs the multi-realm authentication attempt by calling back to a {@link AuthenticationStrategy} object 193 * as each realm is consulted for {@code AuthenticationInfo} for the specified {@code token}. 194 * 195 * @param realms the multiple realms configured on this Authenticator instance. 196 * @param token the submitted AuthenticationToken representing the subject's (user's) log-in principals and credentials. 197 * @return an aggregated AuthenticationInfo instance representing account data across all the successfully 198 * consulted realms. 199 */ 200 protected AuthenticationInfo doMultiRealmAuthentication(Collection<Realm> realms, AuthenticationToken token) { 201 202 AuthenticationStrategy strategy = getAuthenticationStrategy(); 203 204 AuthenticationInfo aggregate = strategy.beforeAllAttempts(realms, token); 205 206 if (LOGGER.isTraceEnabled()) { 207 LOGGER.trace("Iterating through {} realms for PAM authentication", realms.size()); 208 } 209 210 for (Realm realm : realms) { 211 212 try { 213 aggregate = strategy.beforeAttempt(realm, token, aggregate); 214 } catch (ShortCircuitIterationException shortCircuitSignal) { 215 // Break from continuing with subsequent realms on receiving 216 // short circuit signal from strategy 217 break; 218 } 219 220 if (realm.supports(token)) { 221 222 LOGGER.trace("Attempting to authenticate token [{}] using realm [{}]", token, realm); 223 224 AuthenticationInfo info = null; 225 Throwable t = null; 226 try { 227 info = realm.getAuthenticationInfo(token); 228 } catch (Throwable throwable) { 229 t = throwable; 230 if (LOGGER.isDebugEnabled()) { 231 String msg = "Realm [" + realm + "] threw an exception during a multi-realm authentication attempt:"; 232 LOGGER.debug(msg, t); 233 } 234 } 235 236 aggregate = strategy.afterAttempt(realm, token, info, aggregate, t); 237 238 } else { 239 LOGGER.debug("Realm [{}] does not support token {}. Skipping realm.", realm, token); 240 } 241 } 242 243 aggregate = strategy.afterAllAttempts(token, aggregate); 244 245 return aggregate; 246 } 247 248 249 /** 250 * Attempts to authenticate the given token by iterating over the internal collection of 251 * {@link Realm}s. For each realm, first the {@link Realm#supports(org.apache.shiro.authc.AuthenticationToken)} 252 * method will be called to determine if the realm supports the {@code authenticationToken} method argument. 253 * <p/> 254 * If a realm does support 255 * the token, its {@link Realm#getAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)} 256 * method will be called. If the realm returns a non-null account, the token will be 257 * considered authenticated for that realm and the account data recorded. If the realm returns {@code null}, 258 * the next realm will be consulted. If no realms support the token or all supporting realms return null, 259 * an {@link AuthenticationException} will be thrown to indicate that the user could not be authenticated. 260 * <p/> 261 * After all realms have been consulted, the information from each realm is aggregated into a single 262 * {@link AuthenticationInfo} object and returned. 263 * 264 * @param authenticationToken the token containing the authentication principal and credentials for the 265 * user being authenticated. 266 * @return account information attributed to the authenticated user. 267 * @throws IllegalStateException if no realms have been configured at the time this method is invoked 268 * @throws AuthenticationException if the user could not be authenticated or the user is denied authentication 269 * for the given principal and credentials. 270 */ 271 protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException { 272 assertRealmsConfigured(); 273 Collection<Realm> realms = getRealms(); 274 if (realms.size() == 1) { 275 return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken); 276 } else { 277 return doMultiRealmAuthentication(realms, authenticationToken); 278 } 279 } 280 281 /** 282 * First calls <code>super.onLogout(principals)</code> to ensure a logout notification is issued, and for each 283 * wrapped {@code Realm} that implements the {@link LogoutAware LogoutAware} interface, calls 284 * <code>((LogoutAware)realm).onLogout(principals)</code> to allow each realm the opportunity to perform 285 * logout/cleanup operations during an user-logout. 286 * <p/> 287 * Shiro's Realm implementations all implement the {@code LogoutAware} interface by default and can be 288 * overridden for realm-specific logout logic. 289 * 290 * @param principals the application-specific Subject/user identifier. 291 */ 292 public void onLogout(PrincipalCollection principals) { 293 super.onLogout(principals); 294 Collection<Realm> realms = getRealms(); 295 if (!CollectionUtils.isEmpty(realms)) { 296 for (Realm realm : realms) { 297 if (realm instanceof LogoutAware) { 298 ((LogoutAware) realm).onLogout(principals); 299 } 300 } 301 } 302 } 303 }