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 * @see AtLeastOneSuccessfulStrategy AtLeastOneSuccessfulAuthenticationStrategy
036 * @since 0.9
037 */
038 public class FirstSuccessfulStrategy extends AbstractAuthenticationStrategy {
039
040 /**
041 * Returns {@code null} immediately, relying on this class's {@link #merge merge} implementation to return
042 * only the first {@code info} object it encounters, ignoring all subsequent ones.
043 */
044 public AuthenticationInfo beforeAllAttempts(Collection<? extends Realm> realms, AuthenticationToken token) throws AuthenticationException {
045 return null;
046 }
047
048 /**
049 * Returns the specified {@code aggregate} instance if is non null and valid (that is, has principals and they are
050 * not empty) immediately, or, if it is null or not valid, the {@code info} argument is returned instead.
051 * <p/>
052 * This logic ensures that the first valid info encountered is the one retained and all subsequent ones are ignored,
053 * since this strategy mandates that only the info from the first successfully authenticated realm be used.
054 */
055 protected AuthenticationInfo merge(AuthenticationInfo info, AuthenticationInfo aggregate) {
056 if (aggregate != null && !CollectionUtils.isEmpty(aggregate.getPrincipals())) {
057 return aggregate;
058 }
059 return info != null ? info : aggregate;
060 }
061 }