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 */
019package org.apache.isis.viewer.restfulobjects.server.authentication;
020
021import java.util.Collections;
022import java.util.List;
023
024import javax.servlet.ServletRequest;
025import javax.servlet.ServletResponse;
026import javax.servlet.http.HttpServletRequest;
027import javax.servlet.http.HttpSession;
028
029import org.apache.isis.core.commons.authentication.AuthenticationSession;
030import org.apache.isis.core.runtime.authentication.standard.SimpleSession;
031import org.apache.isis.core.webapp.auth.AuthenticationSessionStrategyAbstract;
032
033import com.google.common.base.Splitter;
034import com.google.common.base.Strings;
035import com.google.common.collect.Lists;
036
037/**
038 * Implements a home-grown protocol, whereby the user id and roles are passed
039 * using custom headers.
040 * 
041 * <p>
042 * Does not bind the {@link AuthenticationSession} onto the {@link HttpSession}.
043 */
044public class AuthenticationSessionStrategyHeader extends AuthenticationSessionStrategyAbstract {
045
046    @Override
047    public AuthenticationSession lookupValid(final ServletRequest servletRequest, final ServletResponse servletResponse) {
048
049        final HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
050        final String user = httpServletRequest.getHeader("isis.user");
051        final List<String> roles = rolesFrom(httpServletRequest);
052
053        if (Strings.isNullOrEmpty(user)) {
054            return null;
055        }
056        return new SimpleSession(user, roles);
057    }
058
059    protected List<String> rolesFrom(final HttpServletRequest httpServletRequest) {
060        final String rolesStr = httpServletRequest.getHeader("isis.roles");
061        if (rolesStr == null) {
062            return Collections.emptyList();
063        }
064        return Lists.newArrayList(Splitter.on(",").split(rolesStr));
065    }
066}