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.AuthenticationException;
022 import org.apache.shiro.authc.AuthenticationInfo;
023 import org.apache.shiro.authc.AuthenticationToken;
024 import org.apache.shiro.realm.Realm;
025 import org.apache.shiro.util.CollectionUtils;
026
027 import java.util.Collection;
028
029 /**
030 * {@link AuthenticationStrategy} implementation that only accepts the account data from
031 * the first successfully consulted Realm and ignores all subsequent realms. This is slightly
032 * different behavior than {@link AtLeastOneSuccessfulStrategy}, so please review both to see
033 * which one meets your needs better.
034 *
035 * @author Les Hazlewood
036 * @see AtLeastOneSuccessfulStrategy AtLeastOneSuccessfulAuthenticationStrategy
037 * @since 0.9
038 */
039 public class FirstSuccessfulStrategy extends AbstractAuthenticationStrategy {
040
041 /**
042 * Returns {@code null} immediately, relying on this class's {@link #merge merge} implementation to return
043 * only the first {@code info} object it encounters, ignoring all subsequent ones.
044 */
045 public AuthenticationInfo beforeAllAttempts(Collection<? extends Realm> realms, AuthenticationToken token) throws AuthenticationException {
046 return null;
047 }
048
049 /**
050 * Returns the specified {@code aggregate} instance if is non null and valid (that is, has principals and they are
051 * not empty) immediately, or, if it is null or not valid, the {@code info} argument is returned instead.
052 * <p/>
053 * This logic ensures that the first valid info encountered is the one retained and all subsequent ones are ignored,
054 * since this strategy mandates that only the info from the first successfully authenticated realm be used.
055 */
056 protected AuthenticationInfo merge(AuthenticationInfo info, AuthenticationInfo aggregate) {
057 if (aggregate != null && !CollectionUtils.isEmpty(aggregate.getPrincipals())) {
058 return aggregate;
059 }
060 return info != null ? info : aggregate;
061 }
062 }