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