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