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.Set;
023
024import org.apache.shiro.authc.AuthenticationException;
025import org.apache.shiro.authc.AuthenticationInfo;
026import org.apache.shiro.authc.AuthenticationToken;
027import org.apache.shiro.authc.SimpleAuthenticationInfo;
028import org.apache.shiro.realm.AuthenticatingRealm;
029import org.apache.shiro.subject.SimplePrincipalCollection;
030import org.fcrepo.auth.common.ContainerRolesPrincipalProvider.ContainerRolesPrincipal;
031import org.slf4j.Logger;
032
033/**
034 * @author peichman
035 */
036public class ServletContainerAuthenticatingRealm extends AuthenticatingRealm {
037
038    private static final Logger log = getLogger(ServletContainerAuthenticatingRealm.class);
039
040    @Override
041    public String getName() {
042        return "servlet container authentication";
043    }
044
045    @Override
046    protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken token)
047            throws AuthenticationException {
048        final ContainerAuthToken authToken = (ContainerAuthToken) token;
049        final SimplePrincipalCollection principals = new SimplePrincipalCollection();
050        log.debug("Creating principals from servlet container principal and roles");
051        // container-managed auth username
052        principals.add(authToken.getPrincipal(), getName());
053        // container-managed auth roles
054        final Set<ContainerRolesPrincipal> roles = authToken.getRoles();
055        if (!roles.isEmpty()) {
056            principals.addAll(roles, getName());
057        }
058        return new SimpleAuthenticationInfo(principals, ContainerAuthToken.AUTHORIZED);
059    }
060
061    @Override
062    public boolean supports(final AuthenticationToken token) {
063        return token instanceof ContainerAuthToken;
064    }
065
066}