From aa9eeb45fad212e64f4d64caa9c6d5366988a8ed Mon Sep 17 00:00:00 2001 From: Cleverson Sacramento Date: Tue, 2 Dec 2014 12:07:50 -0200 Subject: [PATCH] FWK-208: Tratamento de uso de sessão com REST --- impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/RESTConfig.java | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/RESTSecurityConfig.java | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/SessionNotAllowedListener.java | 98 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/SessionNotPermittedListener.java | 60 ------------------------------------------------------------ impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/security/BasicAuthFilter.java | 1 + impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/security/RESTSecurityConfig.java | 62 -------------------------------------------------------------- impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/security/TokenAuthFilter.java | 1 + impl/extension/rest/src/main/resources/demoiselle-rest-bundle.properties | 1 + impl/extension/rest/src/test/java/security/authentication/basic/BasicAuthenticationFilterTest.java | 13 +++++-------- impl/extension/rest/src/test/java/test/Tests.java | 2 +- 10 files changed, 224 insertions(+), 131 deletions(-) create mode 100644 impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/RESTConfig.java create mode 100644 impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/RESTSecurityConfig.java create mode 100644 impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/SessionNotAllowedListener.java delete mode 100644 impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/SessionNotPermittedListener.java delete mode 100644 impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/security/RESTSecurityConfig.java diff --git a/impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/RESTConfig.java b/impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/RESTConfig.java new file mode 100644 index 0000000..e54aa42 --- /dev/null +++ b/impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/RESTConfig.java @@ -0,0 +1,55 @@ +/* + * Demoiselle Framework + * Copyright (C) 2010 SERPRO + * ---------------------------------------------------------------------------- + * This file is part of Demoiselle Framework. + * + * Demoiselle Framework is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License version 3 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License version 3 + * along with this program; if not, see + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Demoiselle. + * + * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ +package br.gov.frameworkdemoiselle.internal.configuration; + +import java.io.Serializable; + +import br.gov.frameworkdemoiselle.annotation.Name; +import br.gov.frameworkdemoiselle.configuration.Configuration; + +@Configuration(prefix = "frameworkdemoiselle") +public class RESTConfig implements Serializable { + + private static final long serialVersionUID = 1L; + + @Name("session.allowed") + private boolean sessionAllowed = false; + + public boolean isSessionAllowed() { + return sessionAllowed; + } +} diff --git a/impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/RESTSecurityConfig.java b/impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/RESTSecurityConfig.java new file mode 100644 index 0000000..1992eb7 --- /dev/null +++ b/impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/internal/configuration/RESTSecurityConfig.java @@ -0,0 +1,62 @@ +/* + * Demoiselle Framework + * Copyright (C) 2010 SERPRO + * ---------------------------------------------------------------------------- + * This file is part of Demoiselle Framework. + * + * Demoiselle Framework is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License version 3 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License version 3 + * along with this program; if not, see + * or write to the Free Software Foundation, Inc., 51 Franklin Street, + * Fifth Floor, Boston, MA 02110-1301, USA. + * ---------------------------------------------------------------------------- + * Este arquivo é parte do Framework Demoiselle. + * + * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou + * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação + * do Software Livre (FSF). + * + * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA + * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou + * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português + * para maiores detalhes. + * + * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título + * "LICENCA.txt", junto com esse programa. Se não, acesse + * ou escreva para a Fundação do Software Livre (FSF) Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + */ +package br.gov.frameworkdemoiselle.internal.configuration; + +import java.io.Serializable; + +import br.gov.frameworkdemoiselle.annotation.Name; +import br.gov.frameworkdemoiselle.configuration.Configuration; + +@Configuration(prefix = "frameworkdemoiselle.security") +public class RESTSecurityConfig implements Serializable { + + private static final long serialVersionUID = 1L; + + @Name("basic.filter.active") + private boolean basicFilterActive = true; + + @Name("token.filter.active") + private boolean tokenFilterActive = true; + + public boolean isBasicFilterActive() { + return basicFilterActive; + } + + public boolean isTokenFilterActive() { + return tokenFilterActive; + } +} diff --git a/impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/SessionNotAllowedListener.java b/impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/SessionNotAllowedListener.java new file mode 100644 index 0000000..b263648 --- /dev/null +++ b/impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/SessionNotAllowedListener.java @@ -0,0 +1,98 @@ +package br.gov.frameworkdemoiselle.internal.implementation; + +import static javax.servlet.SessionTrackingMode.URL; + +import java.util.HashSet; +import java.util.Set; +import java.util.logging.Logger; + +import javax.enterprise.event.Observes; +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; +import javax.servlet.SessionTrackingMode; +import javax.servlet.annotation.WebListener; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import javax.servlet.http.HttpSessionEvent; +import javax.servlet.http.HttpSessionListener; + +import br.gov.frameworkdemoiselle.internal.configuration.RESTConfig; +import br.gov.frameworkdemoiselle.transaction.BeforeTransactionComplete; +import br.gov.frameworkdemoiselle.util.Beans; +import br.gov.frameworkdemoiselle.util.NameQualifier; +import br.gov.frameworkdemoiselle.util.ResourceBundle; + +@WebListener +public class SessionNotAllowedListener implements ServletContextListener, HttpSessionListener { + + private static final String ATTR_NAME = "br.gov.frameworkdemoiselle.SESSION_NOT_ALLOWED"; + + private static final String ATTR_VALUE = "created"; + + private transient RESTConfig config; + + private transient ResourceBundle bundle; + + private transient Logger logger; + + public void contextInitialized(ServletContextEvent event) { + if (!getConfig().isSessionAllowed()) { + Set modes = new HashSet(); + modes.add(URL); + event.getServletContext().setSessionTrackingModes(modes); + } + } + + public void contextDestroyed(ServletContextEvent event) { + } + + @Override + public void sessionCreated(HttpSessionEvent event) { + if (!getConfig().isSessionAllowed()) { + Beans.getReference(HttpServletRequest.class).setAttribute(ATTR_NAME, ATTR_VALUE); + } + } + + @Override + public void sessionDestroyed(HttpSessionEvent event) { + } + + public void beforeTransactionComplete(@Observes BeforeTransactionComplete event, HttpServletRequest request) { + if (!getConfig().isSessionAllowed() && ATTR_VALUE.equals(request.getAttribute(ATTR_NAME))) { + invalidateSesstion(request); + throw new IllegalStateException(getBundle().getString("session-not-allowed")); + } + } + + private void invalidateSesstion(HttpServletRequest request) { + HttpSession session = request.getSession(false); + + if (session != null) { + session.invalidate(); + } + } + + private RESTConfig getConfig() { + if (config == null) { + config = Beans.getReference(RESTConfig.class); + } + + return config; + } + + private ResourceBundle getBundle() { + if (bundle == null) { + bundle = Beans.getReference(ResourceBundle.class, new NameQualifier("demoiselle-rest-bundle")); + } + + return bundle; + } + + private Logger getLogger() { + if (logger == null) { + logger = Beans.getReference(Logger.class, new NameQualifier("br.gov.frameworkdemoiselle.util")); + } + + return logger; + } +} diff --git a/impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/SessionNotPermittedListener.java b/impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/SessionNotPermittedListener.java deleted file mode 100644 index 1a066f4..0000000 --- a/impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/internal/implementation/SessionNotPermittedListener.java +++ /dev/null @@ -1,60 +0,0 @@ -package br.gov.frameworkdemoiselle.internal.implementation; - -import static javax.servlet.SessionTrackingMode.URL; - -import java.util.HashSet; -import java.util.Set; - -import javax.enterprise.event.Observes; -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; -import javax.servlet.SessionTrackingMode; -import javax.servlet.annotation.WebListener; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; -import javax.servlet.http.HttpSessionEvent; -import javax.servlet.http.HttpSessionListener; - -import br.gov.frameworkdemoiselle.transaction.BeforeTransactionComplete; -import br.gov.frameworkdemoiselle.util.Beans; - -@WebListener -public class SessionNotPermittedListener implements ServletContextListener, HttpSessionListener { - - private static final String ATTR_NAME = "br.gov.frameworkdemoiselle.SESSION_NOT_PERMITTED"; - - private static final String ATTR_VALUE = "created"; - - public void contextInitialized(ServletContextEvent event) { - Set modes = new HashSet(); - modes.add(URL); - event.getServletContext().setSessionTrackingModes(modes); - } - - public void contextDestroyed(ServletContextEvent event) { - } - - @Override - public void sessionCreated(HttpSessionEvent event) { - Beans.getReference(HttpServletRequest.class).setAttribute(ATTR_NAME, ATTR_VALUE); - } - - @Override - public void sessionDestroyed(HttpSessionEvent event) { - } - - public void beforeTransactionComplete(@Observes BeforeTransactionComplete event, HttpServletRequest request) { - if (ATTR_VALUE.equals(request.getAttribute(ATTR_NAME))) { - invalidateSesstion(request); - throw new IllegalStateException("Session use is not permitted."); - } - } - - private void invalidateSesstion(HttpServletRequest request) { - HttpSession session = request.getSession(false); - - if (session != null) { - session.invalidate(); - } - } -} diff --git a/impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/security/BasicAuthFilter.java b/impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/security/BasicAuthFilter.java index 52760b0..5bed66b 100644 --- a/impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/security/BasicAuthFilter.java +++ b/impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/security/BasicAuthFilter.java @@ -41,6 +41,7 @@ import javax.servlet.http.HttpServletResponse; import org.apache.commons.codec.binary.Base64; +import br.gov.frameworkdemoiselle.internal.configuration.RESTSecurityConfig; import br.gov.frameworkdemoiselle.util.Beans; public class BasicAuthFilter extends AbstractHTTPAuthorizationFilter { diff --git a/impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/security/RESTSecurityConfig.java b/impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/security/RESTSecurityConfig.java deleted file mode 100644 index c2e4496..0000000 --- a/impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/security/RESTSecurityConfig.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Demoiselle Framework - * Copyright (C) 2010 SERPRO - * ---------------------------------------------------------------------------- - * This file is part of Demoiselle Framework. - * - * Demoiselle Framework is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public License version 3 - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License version 3 - * along with this program; if not, see - * or write to the Free Software Foundation, Inc., 51 Franklin Street, - * Fifth Floor, Boston, MA 02110-1301, USA. - * ---------------------------------------------------------------------------- - * Este arquivo é parte do Framework Demoiselle. - * - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação - * do Software Livre (FSF). - * - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português - * para maiores detalhes. - * - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título - * "LICENCA.txt", junto com esse programa. Se não, acesse - * ou escreva para a Fundação do Software Livre (FSF) Inc., - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. - */ -package br.gov.frameworkdemoiselle.security; - -import java.io.Serializable; - -import br.gov.frameworkdemoiselle.annotation.Name; -import br.gov.frameworkdemoiselle.configuration.Configuration; - -@Configuration(prefix = "frameworkdemoiselle.security") -public class RESTSecurityConfig implements Serializable { - - private static final long serialVersionUID = 1L; - - @Name("basic.filter.active") - private boolean basicFilterActive = true; - - @Name("token.filter.active") - private boolean tokenFilterActive = true; - - public boolean isBasicFilterActive() { - return basicFilterActive; - } - - public boolean isTokenFilterActive() { - return tokenFilterActive; - } -} diff --git a/impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/security/TokenAuthFilter.java b/impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/security/TokenAuthFilter.java index fcd3839..16fad90 100644 --- a/impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/security/TokenAuthFilter.java +++ b/impl/extension/rest/src/main/java/br/gov/frameworkdemoiselle/security/TokenAuthFilter.java @@ -43,6 +43,7 @@ import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import br.gov.frameworkdemoiselle.internal.configuration.RESTSecurityConfig; import br.gov.frameworkdemoiselle.util.Beans; public class TokenAuthFilter extends AbstractHTTPAuthorizationFilter { diff --git a/impl/extension/rest/src/main/resources/demoiselle-rest-bundle.properties b/impl/extension/rest/src/main/resources/demoiselle-rest-bundle.properties index caaee22..fb072b9 100644 --- a/impl/extension/rest/src/main/resources/demoiselle-rest-bundle.properties +++ b/impl/extension/rest/src/main/resources/demoiselle-rest-bundle.properties @@ -34,5 +34,6 @@ # 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. internal-server-error=Erro interno do servidor +session-not-allowed=O uso de sess\u00F5es n\u00E3o \u00E9 aconselh\u00E1vel em aplia\u00E7\u00F5es REST, mas se mesmo assim voc\u00EA desejar usar defina "frameworkdemoiselle.session.allowed\=true" no demoiselle.properties da aplica\u00E7\u00E3o mapping-violations=Mapeando viola\u00E7\u00F5es com o status HTTP {0} authentication-failed=Falha na autentica\u00E7\u00E3o diff --git a/impl/extension/rest/src/test/java/security/authentication/basic/BasicAuthenticationFilterTest.java b/impl/extension/rest/src/test/java/security/authentication/basic/BasicAuthenticationFilterTest.java index cf41ea5..301ba41 100644 --- a/impl/extension/rest/src/test/java/security/authentication/basic/BasicAuthenticationFilterTest.java +++ b/impl/extension/rest/src/test/java/security/authentication/basic/BasicAuthenticationFilterTest.java @@ -5,12 +5,10 @@ import static org.apache.http.HttpStatus.SC_OK; import static org.apache.http.HttpStatus.SC_UNAUTHORIZED; import static org.junit.Assert.assertEquals; -import java.io.IOException; import java.net.URL; import org.apache.commons.codec.binary.Base64; import org.apache.http.HttpResponse; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; @@ -39,7 +37,7 @@ public class BasicAuthenticationFilterTest { } @Test - public void loginSucessfull() throws ClientProtocolException, IOException { + public void loginSucessfull() throws Exception { CloseableHttpClient client = HttpClientBuilder.create().build(); HttpGet get; HttpResponse response; @@ -61,15 +59,14 @@ public class BasicAuthenticationFilterTest { } @Test - public void loginFailed() throws ClientProtocolException, IOException { + public void loginFailed() throws Exception { String username = "invalid"; String password = "invalid"; - - + HttpPost x = new HttpPost(); x.setEntity(null); - - //HttpEntity entity + + // HttpEntity entity HttpGet get = new HttpGet(deploymentUrl + "/helper"); byte[] encoded = Base64.encodeBase64((username + ":" + password).getBytes()); diff --git a/impl/extension/rest/src/test/java/test/Tests.java b/impl/extension/rest/src/test/java/test/Tests.java index 69679b8..47a94ab 100644 --- a/impl/extension/rest/src/test/java/test/Tests.java +++ b/impl/extension/rest/src/test/java/test/Tests.java @@ -51,6 +51,7 @@ import br.gov.frameworkdemoiselle.InternalServerErrorException; import br.gov.frameworkdemoiselle.NotFoundException; import br.gov.frameworkdemoiselle.ServiceUnavailableException; import br.gov.frameworkdemoiselle.UnprocessableEntityException; +import br.gov.frameworkdemoiselle.internal.configuration.RESTSecurityConfig; import br.gov.frameworkdemoiselle.internal.implementation.AuthenticationExceptionMapper; import br.gov.frameworkdemoiselle.internal.implementation.AuthorizationExceptionMapper; import br.gov.frameworkdemoiselle.internal.implementation.ConstraintViolationExceptionMapper; @@ -59,7 +60,6 @@ import br.gov.frameworkdemoiselle.internal.implementation.HttpViolationException import br.gov.frameworkdemoiselle.internal.implementation.IllegalArgumentExceptionMapper; import br.gov.frameworkdemoiselle.security.AbstractHTTPAuthorizationFilter; import br.gov.frameworkdemoiselle.security.BasicAuthFilter; -import br.gov.frameworkdemoiselle.security.RESTSecurityConfig; import br.gov.frameworkdemoiselle.security.Token; //import br.gov.frameworkdemoiselle.util.BasicAuthFilter; import br.gov.frameworkdemoiselle.security.TokenAuthFilter; -- libgit2 0.21.2