View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.shiro.web.filter.session;
20  
21  import org.apache.shiro.subject.support.DefaultSubjectContext;
22  import org.apache.shiro.web.filter.PathMatchingFilter;
23  
24  import javax.servlet.ServletRequest;
25  import javax.servlet.ServletResponse;
26  
27  /**
28   * A {@code PathMatchingFilter} that will disable creating new Sessions during the request.  This is a useful
29   * filter to place in the front of any filter chains that may result in REST, SOAP or other service invocations that
30   * are not intended to participate in a session.
31   * <p/>
32   * This filter enables the following behavior:
33   * <ol>
34   * <li>If a {@code Subject} does not yet have a Session by the time this filter is called, this filter effectively
35   * disables all calls to {@code subject}.{@link org.apache.shiro.subject.Subject#getSession() getSession()} and
36   * {@code subject}.{@link org.apache.shiro.subject.Subject#getSession(boolean) getSession(true)}.  If either are called
37   * during the request, an exception will be thrown.</li>
38   * <li>
39   * However, if the {@code Subject} already has an associated session before this filter is invoked, either because it
40   * was created in another part of the application, or a filter higher in the chain created one, this filter has no
41   * effect.
42   * </li>
43   * </ol>
44   * Finally, calls to <code>subject.getSession(false)</code> (i.e. a {@code false} boolean value) will be unaffected
45   * and may be called without repercussion in all cases.
46   *
47   * @since 1.2
48   */
49  public class NoSessionCreationFilter extends PathMatchingFilter {
50  
51      @Override
52      protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
53          request.setAttribute(DefaultSubjectContext.SESSION_CREATION_ENABLED, Boolean.FALSE);
54          return true;
55      }
56  }