工具类之Token
程序员文章站
2022-05-16 12:52:13
...
在项目开发中,简易的安全机制可以采用token验证的方式,如下token工具类:
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.commons.lang.RandomStringUtils; import com.sfbm.carmall.constant.Constant; import com.sfbm.core.util.string.StringUtils; public class TokenUtils{ public static final String TOKEN_KEY_NUM = "_TOKEN_NUM"; /** * 生成token值 * @param req * @return */ public static String createToken(String tokenKey, HttpServletRequest req){ HttpSession session = req.getSession(); String token = RandomStringUtils.random(20, Constant.randomChar); session.setAttribute(tokenKey, token); session.setAttribute(tokenKey + TOKEN_KEY_NUM, 0); return token; } /** * 验证token是否正确 * @param req * @return */ public static boolean authTokenIsOk(HttpServletRequest req, String tokenKey, String token){ if(StringUtils.isBlank(token)){ return false; } HttpSession session = req.getSession(); String sessionToken = (String)session.getAttribute(tokenKey); if(StringUtils.equals(sessionToken, token)){ return true; } return false; } /** * 验证token是否正确 * @param req * @return */ public static boolean authTokenNumIsOk(HttpServletRequest req, String tokenKey, String token){ if(StringUtils.isBlank(token)){ return false; } HttpSession session = req.getSession(); //记录下验证的次数 Integer num = (Integer)session.getAttribute(tokenKey + TOKEN_KEY_NUM); if(num < 5){ session.setAttribute(tokenKey + TOKEN_KEY_NUM, num+1); return true; } return false; } }