001/*
002 * Licensed to DuraSpace under one or more contributor license agreements.
003 * See the NOTICE file distributed with this work for additional information
004 * regarding copyright ownership.
005 *
006 * DuraSpace licenses this file to you under the Apache License,
007 * Version 2.0 (the "License"); you may not use this file except in
008 * compliance 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, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.fcrepo.auth.common;
019
020import static org.slf4j.LoggerFactory.getLogger;
021
022import java.util.HashSet;
023import java.util.Set;
024
025import org.apache.http.auth.BasicUserPrincipal;
026import org.apache.shiro.authc.AuthenticationToken;
027import org.fcrepo.auth.common.ContainerRolesPrincipalProvider.ContainerRolesPrincipal;
028import org.slf4j.Logger;
029
030/**
031 * @author peichman
032 */
033public class ContainerAuthToken implements AuthenticationToken {
034
035    private static final Logger log = getLogger(ContainerAuthToken.class);
036
037    public static final String AUTHORIZED = "AUTHORIZED";
038
039    private final BasicUserPrincipal servletUser;
040
041    private final Set<ContainerRolesPrincipal> servletRoles;
042
043    /**
044     * @param servletUsername username returned from servlet container authentication
045     * @param servletRoleNames roles returned from servlet container authentication
046     */
047    public ContainerAuthToken(final String servletUsername, final Set<String> servletRoleNames) {
048        servletUser = new BasicUserPrincipal(servletUsername);
049        log.debug("Setting servlet username {}", servletUsername);
050        this.servletRoles = new HashSet<>();
051        for (String roleName : servletRoleNames) {
052            log.debug("Adding servlet role {} to {}", roleName, servletUsername);
053            this.servletRoles.add(new ContainerRolesPrincipal(roleName));
054        }
055    }
056
057    @Override
058    public Object getPrincipal() {
059        return servletUser;
060    }
061
062    /**
063     * This token represents a user who was already authenticated by the servlet container, so return a constant
064     * credentials string.
065     */
066    @Override
067    public Object getCredentials() {
068        return AUTHORIZED;
069    }
070
071    /**
072     * @return set of principals
073     */
074    public Set<ContainerRolesPrincipal> getRoles() {
075        return servletRoles;
076    }
077
078}