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.shiro.spring.remoting;
020
021import org.aopalliance.intercept.MethodInvocation;
022import org.apache.shiro.SecurityUtils;
023import org.apache.shiro.session.Session;
024import org.apache.shiro.session.mgt.NativeSessionManager;
025import org.apache.shiro.session.mgt.SessionKey;
026import org.apache.shiro.session.mgt.SessionManager;
027import org.apache.shiro.subject.Subject;
028import org.slf4j.Logger;
029import org.slf4j.LoggerFactory;
030import org.springframework.remoting.support.DefaultRemoteInvocationFactory;
031import org.springframework.remoting.support.RemoteInvocation;
032import org.springframework.remoting.support.RemoteInvocationFactory;
033
034import java.io.Serializable;
035
036/**
037 * A {@link RemoteInvocationFactory} that passes the session ID to the server via a
038 * {@link RemoteInvocation} {@link RemoteInvocation#getAttribute(String) attribute}.
039 * This factory is the client-side part of
040 * the Shiro Spring remoting invocation.  A {@link SecureRemoteInvocationExecutor} should
041 * be used to export the server-side remote services to ensure that the appropriate
042 * Subject and Session are bound to the remote thread during execution.
043 *
044 * @since 0.1
045 */
046public class SecureRemoteInvocationFactory extends DefaultRemoteInvocationFactory {
047
048    /**
049     * session id key.
050     */
051    public static final String SESSION_ID_KEY = SecureRemoteInvocationFactory.class.getName() + ".SESSION_ID_KEY";
052
053    /**
054     * host key.
055     */
056    public static final String HOST_KEY = SecureRemoteInvocationFactory.class.getName() + ".HOST_KEY";
057
058    private static final Logger LOGGER = LoggerFactory.getLogger(SecureRemoteInvocationFactory.class);
059    private static final String SESSION_ID_SYSTEM_PROPERTY_NAME = "shiro.session.id";
060
061    private String sessionId;
062
063    public SecureRemoteInvocationFactory() {
064    }
065
066    public SecureRemoteInvocationFactory(String sessionId) {
067        this();
068        this.sessionId = sessionId;
069    }
070
071    /**
072     * Creates a {@link RemoteInvocation} with the current session ID as an
073     * {@link RemoteInvocation#getAttribute(String) attribute}.
074     *
075     * @param mi the method invocation that the remote invocation should be based on.
076     * @return a remote invocation object containing the current session ID as an attribute.
077     */
078    @SuppressWarnings({"checkstyle:CyclomaticComplexity", "checkstyle:NPathComplexity"})
079    public RemoteInvocation createRemoteInvocation(MethodInvocation mi) {
080
081        Serializable sessionId = null;
082        String host = null;
083        boolean sessionManagerMethodInvocation = false;
084
085        //If the calling MI is for a remoting SessionManager delegate, we need to acquire the session ID from the method
086        //argument and NOT interact with SecurityUtils/subject.getSession to avoid a stack overflow
087        Class miDeclaringClass = mi.getMethod().getDeclaringClass();
088        if (SessionManager.class.equals(miDeclaringClass) || NativeSessionManager.class.equals(miDeclaringClass)) {
089            sessionManagerMethodInvocation = true;
090            //for SessionManager calls, all method calls except the 'start' methods require a SessionKey
091            // as the first argument, so just get it from there:
092            if (!mi.getMethod().getName().equals("start")) {
093                SessionKey key = (SessionKey) mi.getArguments()[0];
094                sessionId = key.getSessionId();
095            }
096        }
097
098        //tried the delegate. Use the injected session id if given
099        if (sessionId == null) {
100            sessionId = this.sessionId;
101        }
102
103        // If sessionId is null, only then try the Subject:
104        if (sessionId == null) {
105            try {
106                // HACK Check if can get the securityManager - this'll cause an exception if it's not set
107                SecurityUtils.getSecurityManager();
108                if (!sessionManagerMethodInvocation) {
109                    Subject subject = SecurityUtils.getSubject();
110                    Session session = subject.getSession(false);
111                    if (session != null) {
112                        sessionId = session.getId();
113                        host = session.getHost();
114                    }
115                }
116            } catch (Exception e) {
117                LOGGER.trace("No security manager set. Trying next to get session id from system property");
118            }
119        }
120        //No call to the sessionManager, and the Subject doesn't have a session.  Try a system property
121        //as a last result:
122        if (sessionId == null) {
123            if (LOGGER.isTraceEnabled()) {
124                LOGGER.trace("No Session found for the currently executing subject via subject.getSession(false).  "
125                        + "Attempting to revert back to the 'shiro.session.id' system property...");
126            }
127            sessionId = System.getProperty(SESSION_ID_SYSTEM_PROPERTY_NAME);
128            if (sessionId == null && LOGGER.isTraceEnabled()) {
129                LOGGER.trace("No 'shiro.session.id' system property found.  Heuristics have been exhausted; "
130                        + "RemoteInvocation will not contain a sessionId.");
131            }
132        }
133
134        RemoteInvocation ri = new RemoteInvocation(mi);
135        if (sessionId != null) {
136            ri.addAttribute(SESSION_ID_KEY, sessionId);
137        }
138        if (host != null) {
139            ri.addAttribute(HOST_KEY, host);
140        }
141
142        return ri;
143    }
144}