1 5 package com.opensymphony.webwork.util; 6 7 import com.opensymphony.util.GUID; 8 import com.opensymphony.xwork.util.LocalizedTextUtil; 9 import org.apache.commons.logging.Log; 10 import org.apache.commons.logging.LogFactory; 11 12 import javax.servlet.http.HttpServletRequest ; 13 import javax.servlet.http.HttpSession ; 14 import java.util.Map ; 15 16 17 23 public class TokenHelper { 24 26 29 final public static String DEFAULT_TOKEN_NAME = "webwork.token"; 30 31 34 final public static String TOKEN_NAME_FIELD = "webwork.token.name"; 35 private static final Log LOG = LogFactory.getLog(TokenHelper.class); 36 37 39 44 public static String setToken(HttpServletRequest request) { 45 return setToken(DEFAULT_TOKEN_NAME, request); 46 } 47 48 54 public static String setToken(String tokenName, HttpServletRequest request) { 55 HttpSession session = request.getSession(true); 56 String token = GUID.generateGUID(); 57 session.setAttribute(tokenName, token); 58 59 return token; 60 } 61 62 68 public static String getToken(String tokenName, HttpServletRequest request) { 69 Map params = request.getParameterMap(); 70 String [] tokens = (String []) params.get(tokenName); 71 String token; 72 73 if ((tokens == null) || (tokens.length < 1)) { 74 LOG.warn("Could not find token mapped to token name " + tokenName); 75 76 return null; 77 } 78 79 token = tokens[0]; 80 81 return token; 82 } 83 84 89 public static String getTokenName(HttpServletRequest request) { 90 Map params = request.getParameterMap(); 91 92 if (!params.containsKey(TOKEN_NAME_FIELD)) { 93 LOG.warn("Could not find token name in params."); 94 95 return null; 96 } 97 98 String [] tokenNames = (String []) params.get(TOKEN_NAME_FIELD); 99 String tokenName; 100 101 if ((tokenNames == null) || (tokenNames.length < 1)) { 102 LOG.warn("Got a null or empty token name."); 103 104 return null; 105 } 106 107 tokenName = tokenNames[0]; 108 109 return tokenName; 110 } 111 112 118 public static boolean validToken(HttpServletRequest request) { 119 String tokenName = getTokenName(request); 120 121 if (tokenName == null) { 122 return false; 123 } 124 125 String token = getToken(tokenName, request); 126 127 if (token == null) { 128 return false; 129 } 130 131 HttpSession session = request.getSession(true); 132 String sessionToken = (String ) session.getAttribute(tokenName); 133 134 if (!token.equals(sessionToken)) { 135 LOG.warn(LocalizedTextUtil.findText(TokenHelper.class, "webwork.invalid.token", request.getLocale(), "Form token {0} does not match the session token {1}.", new Object []{ 136 token, sessionToken 137 })); 138 139 return false; 140 } 141 142 session.removeAttribute(tokenName); 144 145 return true; 146 } 147 } 148 | Popular Tags |