View Javadoc

1   /*
2    * $Id: TokenInterceptor.java 651946 2008-04-27 13:41:38Z apetrelli $
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  
28  import com.opensymphony.xwork2.ActionContext;
29  import com.opensymphony.xwork2.ActionInvocation;
30  import com.opensymphony.xwork2.ValidationAware;
31  import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
32  import com.opensymphony.xwork2.util.LocalizedTextUtil;
33  
34  /***
35   * <!-- START SNIPPET: description -->
36   *
37   * Ensures that only one request per token is processed. This interceptor can make sure that back buttons and double
38   * clicks don't cause un-intended side affects. For example, you can use this to prevent careless users who might double
39   * click on a "checkout" button at an online store. This interceptor uses a fairly primitive technique for when an
40   * invalid token is found: it returns the result <b>invalid.token</b>, which can be mapped in your action configuration.
41   * A more complex implementation, {@link TokenSessionStoreInterceptor}, can provide much better logic for when invalid
42   * tokens are found.
43   *
44   * <p/>
45   *
46   * <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
47   * in the forms that submit to actions protected by this interceptor. Any request that does not provide a token (using
48   * the token tag) will be processed as a request with an invalid token.
49   *
50   * <p/>
51   *
52   * <b>Internationalization Note:</b> The following key could be used to internationalized the action errors generated
53   * by this token interceptor
54   *
55   * <ul>
56   *    <li>struts.messages.invalid.token</li>
57   * </ul>
58   *
59   * <p/>
60   *
61   * <b>NOTE:</b> As this method extends off MethodFilterInterceptor, it is capable of
62   * deciding if it is applicable only to selective methods in the action class. See
63   * <code>MethodFilterInterceptor</code> for more info.
64   *
65   * <!-- END SNIPPET: description -->
66   *
67   * <p/> <u>Interceptor parameters:</u>
68   *
69   * <!-- START SNIPPET: parameters -->
70   *
71   * <ul>
72   *
73   * <li>None</li>
74   *
75   * </ul>
76   *
77   * <!-- END SNIPPET: parameters -->
78   *
79   * <p/> <u>Extending the interceptor:</u>
80   *
81   * <p/>
82   *
83   * <!-- START SNIPPET: extending -->
84   *
85   * While not very common for users to extend, this interceptor is extended by the {@link TokenSessionStoreInterceptor}.
86   * The {@link #handleInvalidToken}  and {@link #handleValidToken} methods are protected and available for more
87   * interesting logic, such as done with the token session interceptor.
88   *
89   * <!-- END SNIPPET: extending -->
90   *
91   * <p/> <u>Example code:</u>
92   *
93   * <pre>
94   * <!-- START SNIPPET: example -->
95   *
96   * &lt;action name="someAction" class="com.examples.SomeAction"&gt;
97   *     &lt;interceptor-ref name="token"/&gt;
98   *     &lt;interceptor-ref name="basicStack"/&gt;
99   *     &lt;result name="success"&gt;good_result.ftl&lt;/result&gt;
100  * &lt;/action&gt;
101  *
102  * &lt;-- In this case, myMethod of the action class will not
103  *        get checked for invalidity of token --&gt;
104  * &lt;action name="someAction" class="com.examples.SomeAction"&gt;
105  *     &lt;interceptor-ref name="token"&gt;
106  *        &lt;param name="excludeMethods"&gt;myMethod&lt;/param&gt;
107  *     &lt;/interceptor-ref name="token"/&gt;
108  *     &lt;interceptor-ref name="basicStack"/&gt;
109  *     &lt;result name="success"&gt;good_result.ftl&lt;/result&gt;
110  * &lt;/action&gt;
111  *
112  * <!-- END SNIPPET: example -->
113  * </pre>
114  *
115  * @see TokenSessionStoreInterceptor
116  * @see TokenHelper
117  */
118 public class TokenInterceptor extends MethodFilterInterceptor {
119 
120     private static final long serialVersionUID = -6680894220590585506L;
121 
122     public static final String INVALID_TOKEN_CODE = "invalid.token";
123 
124     /***
125      * @see com.opensymphony.xwork2.interceptor.MethodFilterInterceptor#doIntercept(com.opensymphony.xwork2.ActionInvocation)
126      */
127     protected String doIntercept(ActionInvocation invocation) throws Exception {
128         if (log.isDebugEnabled()) {
129             log.debug("Intercepting invocation to check for valid transaction token.");
130         }
131 
132         Map session = ActionContext.getContext().getSession();
133 
134         synchronized (session) {
135             if (!TokenHelper.validToken()) {
136                 return handleInvalidToken(invocation);
137             }
138 
139             return handleValidToken(invocation);
140         }
141     }
142 
143     /***
144      * Determines what to do if an invalid token is provided. If the action implements {@link ValidationAware}
145      *
146      * @param invocation the action invocation where the invalid token failed
147      * @return the return code to indicate should be processed
148      * @throws Exception when any unexpected error occurs.
149      */
150     protected String handleInvalidToken(ActionInvocation invocation) throws Exception {
151         Object action = invocation.getAction();
152         String errorMessage = LocalizedTextUtil.findText(this.getClass(), "struts.messages.invalid.token",
153                 invocation.getInvocationContext().getLocale(),
154                 "The form has already been processed or no token was supplied, please try again.", new Object[0]);
155 
156         if (action instanceof ValidationAware) {
157             ((ValidationAware) action).addActionError(errorMessage);
158         } else {
159             log.warn(errorMessage);
160         }
161 
162         return INVALID_TOKEN_CODE;
163     }
164 
165     /***
166      * Called when a valid token is found. This method invokes the action by can be changed to do something more
167      * interesting.
168      *
169      * @param invocation the action invocation
170      * @throws Exception when any unexpected error occurs.
171      */
172     protected String handleValidToken(ActionInvocation invocation) throws Exception {
173         return invocation.invoke();
174     }
175 }