View Javadoc

1   /*
2    * $Id: TokenInterceptor.java 722576 2008-12-02 19:13:26Z musachy $
3    *
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *  http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  package org.apache.struts2.interceptor;
23  
24  import java.util.Map;
25  
26  import org.apache.struts2.util.TokenHelper;
27  import org.apache.struts2.ServletActionContext;
28  
29  import com.opensymphony.xwork2.ActionContext;
30  import com.opensymphony.xwork2.ActionInvocation;
31  import com.opensymphony.xwork2.ValidationAware;
32  import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
33  import com.opensymphony.xwork2.util.LocalizedTextUtil;
34  
35  import javax.servlet.http.HttpSession;
36  
37  /***
38   * <!-- START SNIPPET: description -->
39   *
40   * Ensures that only one request per token is processed. This interceptor can make sure that back buttons and double
41   * clicks don't cause un-intended side affects. For example, you can use this to prevent careless users who might double
42   * click on a "checkout" button at an online store. This interceptor uses a fairly primitive technique for when an
43   * invalid token is found: it returns the result <b>invalid.token</b>, which can be mapped in your action configuration.
44   * A more complex implementation, {@link TokenSessionStoreInterceptor}, can provide much better logic for when invalid
45   * tokens are found.
46   *
47   * <p/>
48   *
49   * <b>Note:</b> To set a token in your form, you should use the <b>token tag</b>. This tag is required and must be used
50   * in the forms that submit to actions protected by this interceptor. Any request that does not provide a token (using
51   * the token tag) will be processed as a request with an invalid token.
52   *
53   * <p/>
54   *
55   * <b>Internationalization Note:</b> The following key could be used to internationalized the action errors generated
56   * by this token interceptor
57   *
58   * <ul>
59   *    <li>struts.messages.invalid.token</li>
60   * </ul>
61   *
62   * <p/>
63   *
64   * <b>NOTE:</b> As this method extends off MethodFilterInterceptor, it is capable of
65   * deciding if it is applicable only to selective methods in the action class. See
66   * <code>MethodFilterInterceptor</code> for more info.
67   *
68   * <!-- END SNIPPET: description -->
69   *
70   * <p/> <u>Interceptor parameters:</u>
71   *
72   * <!-- START SNIPPET: parameters -->
73   *
74   * <ul>
75   *
76   * <li>None</li>
77   *
78   * </ul>
79   *
80   * <!-- END SNIPPET: parameters -->
81   *
82   * <p/> <u>Extending the interceptor:</u>
83   *
84   * <p/>
85   *
86   * <!-- START SNIPPET: extending -->
87   *
88   * While not very common for users to extend, this interceptor is extended by the {@link TokenSessionStoreInterceptor}.
89   * The {@link #handleInvalidToken}  and {@link #handleValidToken} methods are protected and available for more
90   * interesting logic, such as done with the token session interceptor.
91   *
92   * <!-- END SNIPPET: extending -->
93   *
94   * <p/> <u>Example code:</u>
95   *
96   * <pre>
97   * <!-- START SNIPPET: example -->
98   *
99   * &lt;action name="someAction" class="com.examples.SomeAction"&gt;
100  *     &lt;interceptor-ref name="token"/&gt;
101  *     &lt;interceptor-ref name="basicStack"/&gt;
102  *     &lt;result name="success"&gt;good_result.ftl&lt;/result&gt;
103  * &lt;/action&gt;
104  *
105  * &lt;-- In this case, myMethod of the action class will not
106  *        get checked for invalidity of token --&gt;
107  * &lt;action name="someAction" class="com.examples.SomeAction"&gt;
108  *     &lt;interceptor-ref name="token"&gt;
109  *        &lt;param name="excludeMethods"&gt;myMethod&lt;/param&gt;
110  *     &lt;/interceptor-ref name="token"/&gt;
111  *     &lt;interceptor-ref name="basicStack"/&gt;
112  *     &lt;result name="success"&gt;good_result.ftl&lt;/result&gt;
113  * &lt;/action&gt;
114  *
115  * <!-- END SNIPPET: example -->
116  * </pre>
117  *
118  * @see TokenSessionStoreInterceptor
119  * @see TokenHelper
120  */
121 public class TokenInterceptor extends MethodFilterInterceptor {
122 
123     private static final long serialVersionUID = -6680894220590585506L;
124 
125     public static final String INVALID_TOKEN_CODE = "invalid.token";
126 
127     /***
128      * @see com.opensymphony.xwork2.interceptor.MethodFilterInterceptor#doIntercept(com.opensymphony.xwork2.ActionInvocation)
129      */
130     protected String doIntercept(ActionInvocation invocation) throws Exception {
131         if (log.isDebugEnabled()) {
132             log.debug("Intercepting invocation to check for valid transaction token.");
133         }
134 
135         //see WW-2902: we need to use the real HttpSession here, as opposed to the map
136         //that wraps the session, because a new wrap is created on every request
137         HttpSession session = ServletActionContext.getRequest().getSession(true);
138 
139         synchronized (session) {
140             if (!TokenHelper.validToken()) {
141                 return handleInvalidToken(invocation);
142             }
143 
144             return handleValidToken(invocation);
145         }
146     }
147 
148     /***
149      * Determines what to do if an invalid token is provided. If the action implements {@link ValidationAware}
150      *
151      * @param invocation the action invocation where the invalid token failed
152      * @return the return code to indicate should be processed
153      * @throws Exception when any unexpected error occurs.
154      */
155     protected String handleInvalidToken(ActionInvocation invocation) throws Exception {
156         Object action = invocation.getAction();
157         String errorMessage = LocalizedTextUtil.findText(this.getClass(), "struts.messages.invalid.token",
158                 invocation.getInvocationContext().getLocale(),
159                 "The form has already been processed or no token was supplied, please try again.", new Object[0]);
160 
161         if (action instanceof ValidationAware) {
162             ((ValidationAware) action).addActionError(errorMessage);
163         } else {
164             log.warn(errorMessage);
165         }
166 
167         return INVALID_TOKEN_CODE;
168     }
169 
170     /***
171      * Called when a valid token is found. This method invokes the action by can be changed to do something more
172      * interesting.
173      *
174      * @param invocation the action invocation
175      * @throws Exception when any unexpected error occurs.
176      */
177     protected String handleValidToken(ActionInvocation invocation) throws Exception {
178         return invocation.invoke();
179     }
180 }