001/* 002 * Stallion Core: A Modern Web Framework 003 * 004 * Copyright (C) 2015 - 2016 Stallion Software LLC. 005 * 006 * This program is free software: you can redistribute it and/or modify it under the terms of the 007 * GNU General Public License as published by the Free Software Foundation, either version 2 of 008 * the License, or (at your option) any later version. This program is distributed in the hope that 009 * it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of 010 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public 011 * License for more details. You should have received a copy of the GNU General Public License 012 * along with this program. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>. 013 * 014 * 015 * 016 */ 017 018package io.stallion.restfulEndpoints; 019 020import io.stallion.hooks.HookRegistry; 021import io.stallion.requests.PostRequestHookHandler; 022import io.stallion.requests.StRequest; 023import io.stallion.requests.StResponse; 024import io.stallion.settings.Settings; 025 026import javax.servlet.http.Cookie; 027 028import java.util.UUID; 029 030import static io.stallion.utils.Literals.*; 031 032 033public class XSRFHooks extends PostRequestHookHandler { 034 public static final String COOKIE_NAME = "XSRF-TOKEN"; 035 public static final String HEADER_NAME = "X-XSRF-TOKEN"; 036 037 public static boolean checkXsrfAllowed(StRequest request, RestEndpointBase endpoint) { 038 if (!endpoint.shouldCheckXSRF()) { 039 return true; 040 } 041 // Work around for direct access of API endpoints for local testing 042 if (Settings.instance().getEnv().equals("local")) { 043 if (request.getParameter("ignoreXsrf") != null) { 044 return true; 045 } 046 } 047 Cookie cookie = request.getCookie(COOKIE_NAME); 048 if (cookie == null || empty(cookie.getValue())) { 049 return false; 050 } 051 String header = request.getHeader(HEADER_NAME); 052 if (empty(header)) { 053 return false; 054 } 055 return header.equals(cookie.getValue()); 056 } 057 058 public static void register() { 059 HookRegistry.instance().register(new XSRFHooks()); 060 } 061 062 @Override 063 public void handleRequest(StRequest request, StResponse response) { 064 Cookie cookie = request.getCookie(COOKIE_NAME); 065 if (cookie != null && !empty(cookie.getValue())) { 066 return; 067 } 068 response.addCookie(COOKIE_NAME, UUID.randomUUID().toString(), 20 * 365 * 86400); 069 } 070}