From ecc7cab2da26f62d4c53115b5e3a0acdf2d84269 Mon Sep 17 00:00:00 2001 From: PauloGladson Date: Tue, 20 Sep 2016 13:44:09 -0300 Subject: [PATCH] Segurança --- .gitignore | 3 +++ basic/.gitignore | 3 +++ basic/pom.xml | 34 ++++++++++++++++++++++++++++++++++ basic/src/main/java/org/demoiselle/jee/security/basic/impl/SecurityContextImpl.java | 117 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ basic/src/main/java/org/demoiselle/jee/security/basic/impl/TokensManagerImpl.java | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ basic/src/main/resources/demoiselle.properties | 0 core/src/main/resources/demoiselle-core-bundle.properties | 130 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ core/src/main/resources/demoiselle.properties | 5 +++++ jwt/.gitignore | 3 +++ jwt/pom.xml | 33 +++++++++++++++++++++++++++++++++ pom.xml | 3 ++- security/src/main/java/org/demoiselle/jee/security/AfterLoginSuccessful.java | 50 -------------------------------------------------- security/src/main/java/org/demoiselle/jee/security/AfterLogoutSuccessful.java | 50 -------------------------------------------------- security/src/main/java/org/demoiselle/jee/security/Authenticator.java | 89 ----------------------------------------------------------------------------------------- security/src/main/java/org/demoiselle/jee/security/Authorizer.java | 75 --------------------------------------------------------------------------- security/src/main/java/org/demoiselle/jee/security/JaxRsFilter.java | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ security/src/main/java/org/demoiselle/jee/security/SecurityContext.java | 119 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------------------------------------------- security/src/main/java/org/demoiselle/jee/security/TokensManager.java | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ security/src/main/java/org/demoiselle/jee/security/impl/SecurityContextImpl.java | 231 --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- security/src/main/java/org/demoiselle/jee/security/interceptor/LoggedInInterceptor.java | 6 ++---- security/src/main/java/org/demoiselle/jee/security/interceptor/RequiredPermissionInterceptor.java | 1 - security/src/main/java/org/demoiselle/jee/security/interceptor/RequiredRoleInterceptor.java | 1 - security/src/main/resources/demoiselle-security-bundle.properties | 130 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ security/src/main/resources/demoiselle.properties | 0 ws/src/main/java/org/demoiselle/jee/ws/JaxRsFilter.java | 8 +++----- 25 files changed, 695 insertions(+), 568 deletions(-) create mode 100644 basic/.gitignore create mode 100644 basic/pom.xml create mode 100644 basic/src/main/java/org/demoiselle/jee/security/basic/impl/SecurityContextImpl.java create mode 100644 basic/src/main/java/org/demoiselle/jee/security/basic/impl/TokensManagerImpl.java create mode 100644 basic/src/main/resources/demoiselle.properties create mode 100644 core/src/main/resources/demoiselle-core-bundle.properties create mode 100644 core/src/main/resources/demoiselle.properties create mode 100644 jwt/.gitignore create mode 100644 jwt/pom.xml delete mode 100644 security/src/main/java/org/demoiselle/jee/security/AfterLoginSuccessful.java delete mode 100644 security/src/main/java/org/demoiselle/jee/security/AfterLogoutSuccessful.java delete mode 100644 security/src/main/java/org/demoiselle/jee/security/Authenticator.java delete mode 100644 security/src/main/java/org/demoiselle/jee/security/Authorizer.java create mode 100644 security/src/main/java/org/demoiselle/jee/security/JaxRsFilter.java create mode 100644 security/src/main/java/org/demoiselle/jee/security/TokensManager.java delete mode 100644 security/src/main/java/org/demoiselle/jee/security/impl/SecurityContextImpl.java create mode 100644 security/src/main/resources/demoiselle-security-bundle.properties create mode 100644 security/src/main/resources/demoiselle.properties diff --git a/.gitignore b/.gitignore index 28414e7..496d42b 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,6 @@ /security/target/ /.project /.settings/ +/basic/target/ +/basic (cópia)/target/ +/jwt/target/ \ No newline at end of file diff --git a/basic/.gitignore b/basic/.gitignore new file mode 100644 index 0000000..ddd6d6d --- /dev/null +++ b/basic/.gitignore @@ -0,0 +1,3 @@ +/.settings/ +/.classpath +/.project diff --git a/basic/pom.xml b/basic/pom.xml new file mode 100644 index 0000000..135bb87 --- /dev/null +++ b/basic/pom.xml @@ -0,0 +1,34 @@ + + + 4.0.0 + org.demoiselle.jee + demoiselle-security-basic + 3.0.0-SNAPSHOT + jar + + UTF-8 + 1.8 + 1.8 + + + + + ${project.groupId} + demoiselle-core + ${project.version} + + + + ${project.groupId} + demoiselle-ws + ${project.version} + + + + ${project.groupId} + demoiselle-security + ${project.version} + + + + diff --git a/basic/src/main/java/org/demoiselle/jee/security/basic/impl/SecurityContextImpl.java b/basic/src/main/java/org/demoiselle/jee/security/basic/impl/SecurityContextImpl.java new file mode 100644 index 0000000..f7ebc9a --- /dev/null +++ b/basic/src/main/java/org/demoiselle/jee/security/basic/impl/SecurityContextImpl.java @@ -0,0 +1,117 @@ +package org.demoiselle.jee.security.basic.impl; + +import javax.enterprise.context.Dependent; +import java.io.Serializable; +import java.security.Principal; +import java.util.Map; +import java.util.Set; +import javax.inject.Inject; +import org.demoiselle.jee.core.util.ResourceBundle; +import org.demoiselle.jee.security.SecurityContext; +import org.demoiselle.jee.security.TokensManager; +import org.demoiselle.jee.security.exception.NotLoggedInException; + +/** + *

+ * This is the default implementation of {@link SecurityContext} interface. + *

+ * + * @author SERPRO + */ +@Dependent +public class SecurityContextImpl implements SecurityContext { + + private static final long serialVersionUID = 1L; + + private String token; + + private Principal user; + + @Inject + private TokensManager tm; + + @Inject + private ResourceBundle bundle; + + /** + * @see org.demoiselle.security.SecurityContext#hasPermission(String, + * String) + */ + @Override + public boolean hasPermission(String resource, String operation) { + boolean result = true; + + return result; + } + + /** + * @see org.demoiselle.security.SecurityContext#hasRole(String) + */ + @Override + public boolean hasRole(String role) { + boolean result = true; + + return result; + } + + /** + * @see org.demoiselle.security.SecurityContext#isLoggedIn() + */ + @Override + public boolean isLoggedIn() { + return getUser() != null; + } + + /** + * @see org.demoiselle.security.SecurityContext#getUser() + */ + @Override + public Principal getUser() { + return this.user; + } + + public void checkLoggedIn() throws NotLoggedInException { + if (!isLoggedIn()) { + throw new NotLoggedInException(bundle.getString("user-not-authenticated")); + } + } + + @Override + public void setRoles(Set roles) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + @Override + public void setPermission(Map permissions) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + @Override + public Set getResources(String operation) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + @Override + public Set getOperations(String resources) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + @Override + public void setUser(Principal principal) { + this.token = tm.create(principal); + this.user = principal; + } + + @Override + public String getToken() { + return token; + } + + @Override + public void setToken(String token) { + this.user = tm.getUser(token); + this.token = token; + } + + +} diff --git a/basic/src/main/java/org/demoiselle/jee/security/basic/impl/TokensManagerImpl.java b/basic/src/main/java/org/demoiselle/jee/security/basic/impl/TokensManagerImpl.java new file mode 100644 index 0000000..708d945 --- /dev/null +++ b/basic/src/main/java/org/demoiselle/jee/security/basic/impl/TokensManagerImpl.java @@ -0,0 +1,48 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.demoiselle.jee.security.basic.impl; + +import java.security.Principal; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import javax.enterprise.context.Dependent; +import org.demoiselle.jee.security.TokensManager; + +/** + * + * @author 70744416353 + */ +@Dependent +public class TokensManagerImpl implements TokensManager { + + private static ConcurrentHashMap repo = new ConcurrentHashMap<>(); + + @Override + public Principal getUser(String token) { + return repo.get(token); + } + + @Override + public String create(Principal user) { + String value = null; + if (!repo.containsValue(user)) { + value = UUID.randomUUID().toString(); + repo.put(value, user); + } + return value; + } + + @Override + public void remove(String token) { + repo.remove(token); + } + + @Override + public boolean validate(String token) { + return repo.containsKey(token); + } + +} diff --git a/basic/src/main/resources/demoiselle.properties b/basic/src/main/resources/demoiselle.properties new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/basic/src/main/resources/demoiselle.properties diff --git a/core/src/main/resources/demoiselle-core-bundle.properties b/core/src/main/resources/demoiselle-core-bundle.properties new file mode 100644 index 0000000..eb15108 --- /dev/null +++ b/core/src/main/resources/demoiselle-core-bundle.properties @@ -0,0 +1,130 @@ +# 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 \u00E9 parte do Framework Demoiselle. +# +# O Framework Demoiselle \u00E9 um software livre; voc\u00EA pode redistribu\u00ED-lo e/ou +# modific\u00E1-lo dentro dos termos da GNU LGPL vers\u00E3o 3 como publicada pela Funda\u00E7\u00E3o +# do Software Livre (FSF). +# +# Este programa \u00E9 distribu\u00EDdo na esperan\u00E7a que possa ser \u00FAtil, mas SEM NENHUMA +# GARANTIA; sem uma garantia impl\u00EDcita de ADEQUA\u00C7\u00C3O a qualquer MERCADO ou +# APLICA\u00C7\u00C3O EM PARTICULAR. Veja a Licen\u00E7a P\u00FAblica Geral GNU/LGPL em portugu\u00EAs +# para maiores detalhes. +# +# Voc\u00EA deve ter recebido uma c\u00F3pia da GNU LGPL vers\u00E3o 3, sob o t\u00EDtulo +# "LICENCA.txt", junto com esse programa. Se n\u00E3o, acesse +# ou escreva para a Funda\u00E7\u00E3o do Software Livre (FSF) Inc., +# 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + +version=${project.version} +engine-on=Iniciando o Demoiselle Framework ${project.version} (Neo) +resource-not-found=Arquivo {0} n\u00E3o foi encontrado +key-not-found=A chave {0} n\u00E3o foi encontrada +ambiguous-strategy-resolution=Foi detectada ambiguidade da interface {0} com as seguintes implementa\u00E7\u00F5es\: {1}. Para resolver o conflito, defina explicitamente a implementa\u00E7\u00E3o no demoiselle.properties. +ambiguous-bean-resolution=Falha ao obter {0} pois foi detectada ambiguidade nas seguintes implementa\u00E7\u00F5es\: {1} +bean-not-found=Voc\u00EA est\u00E1 tentando obter um objeto n\u00E3o reconhecido pelo CDI via Beans.getReference({0}) +store-not-found=O objeto do tipo [{0}] n\u00E3o pode ser armazenado no escopo indicado\: {1} +more-than-one-exceptionhandler-defined-for-same-class=Foi definido mais de um m\u00E9todo na classe {0} para tratar a exce\u00E7\u00E3o {1} +handling-exception=Tratando a exce\u00E7\u00E3o {0} +taking-off=O Demoiselle ${project.version} decolou +engine-off=Desligando os motores do Demoiselle ${project.version} +setting-up-bean-manager=BeanManager dispon\u00EDvel atrav\u00E9s do utilit\u00E1rio {0} + +user-transaction-lookup-fail=N\u00E3o foi encontrada nenhuma transa\u00E7\u00E3o com o nome {0} no contexto JNDI +transactional-execution=Execu\u00E7\u00E3o transacional de {0} +begin-transaction=Transa\u00E7\u00E3o iniciada +transaction-marked-rollback=Transa\u00E7\u00E3o marcada para rollback [{0}] +transaction-already-finalized=A transa\u00E7\u00E3o j\u00E1 havia sido finalizada +transaction-commited=Transa\u00E7\u00E3o finalizada com sucesso +transaction-rolledback=Transa\u00E7\u00E3o finalizada com rollback + +bootstrap.configuration.processing=Processando {0} +bootstrap-context-already-managed=O contexto {0} para o escopo {1} j\u00E1 foi adicionado +bootstrap-context-added=Adicionando o contexto {0} para o escopo {1} + +loading-configuration-class=Carregando a classe de configura\u00E7\u00E3o {0} +configuration-field-loaded={0}: {2} +configuration-attribute-is-mandatory=A configura\u00E7\u00E3o {0} \u00E9 obrigat\u00F3ria, mas n\u00E3o foi encontrada em {1} +configuration-name-attribute-cant-be-empty=A nota\u00E7\u00E3o @Name n\u00E3o pode estar em branco +configuration-generic-extraction-error=Ocorreu um erro durante a extra\u00E7\u00E3o do tipo {0} com o extrator {1} +configuration-dot-after-prefix=N\u00E3o \u00E9 necess\u00E1rio adicionar o ponto ap\u00F3s o prefixo para uma classe de configura\u00E7\u00E3o. \u00C9 recomendado que sejam retirados, pois poder\u00E3o causar erros em vers\u00F5es futuras do Framework. +configuration-key-not-found={0}\: [n\u00E3o encontrada] +configuration-extractor-not-found=N\u00E3o foi poss\u00EDvel encontrar a classe extratora para o atributo {0}. Implemente a interface {1} para criar sua classe extratora. +configuration-not-conversion=N\u00E3o \u00E9 poss\u00EDvel converter o valor {0} para o tipo {1} + +transaction-not-defined=Nenhuma transa\u00E7\u00E3o foi definida. Para utilizar @{0} \u00E9 preciso definir a propriedade frameworkdemoiselle.transaction.class com a estrat\u00E9gia de transa\u00E7\u00E3o desejada no arquivo demoiselle.properties +executing-all=Executando m\u00E9todos anotados com @{0} +custom-context-selected=Produzindo inst\u00E2ncia do contexto {0} +custom-context-was-activated=O contexto {0} foi ativado para o escopo {1} +custom-context-was-deactivated=O contexto {0} foi desativado para o escopo {1} +custom-context-already-activated=N\u00E3o foi poss\u00EDvel ativar o contexto {0}, o escopo {1} j\u00E1 est\u00E1 ativo no contexto {2} +custom-context-not-found=N\u00E3o foi encontrado um contexto gerenciado do tipo [{0}] para o escopo [{1}] +custom-context-manager-not-initialized=ContextManager n\u00E3o foi inicializado. Chame [initialize] ao capturar o evento [AfterBeanDiscovery] em uma extens\u00E3o CDI + +error-creating-new-instance-for=Error creating a new instance for "{0}" +executed-successfully={0} execultado com sucesso +must-declare-one-single-parameter=Voc\u00EA deve declarar um par\u00E2metro \u00FAnico em {0} +loading-default-transaction-manager=Carregando o gerenciador de transa\u00E7\u00E3o padr\u00E3o {0} +results-count-greater-page-size=Quantidade de resultados {0} \u00E9 maior que o tamanho da p\u00E1gina {1} +page-result=Resultado paginado [p\u00E1gina\={0}, total de resultados\={1}] +pagination-not-initialized=Pagina\u00E7\u00E3o n\u00E3o inicializada. Inicialize o sistema de pagina\u00E7\u00E3o definindo a p\u00E1gina atual ou o total de resultados ao menos uma vez na requisi\u00E7\u00E3o. +pagination-invalid-value=Valor inv\u00E1lido para paginador: [{0}]. +page=P\u00E1gina [n\u00FAmero\={0}, tamanho\={1}] +processing=Processando\: {0} +processing-fail=Falha no processamento devido a uma exce\u00E7\u00E3o lan\u00E7ada pela aplica\u00E7\u00E3o +for= \ para\: +file-not-found=O arquivo {0} n\u00E3o foi encontrado + +adding-message-to-context=Adicionando uma mensagem no contexto: [{0}] +access-checking=Verificando permiss\u00E3o do usu\u00E1rio {0} para executar a a\u00E7\u00E3o {1} no recurso {2} +access-allowed=O usu\u00E1rio {0} acessou o recurso {2} com a a\u00E7\u00E3o {1} +access-denied=O usu\u00E1rio {0} n\u00E3o possui permiss\u00E3o para executar a a\u00E7\u00E3o {1} no recurso {2} +access-denied-ui=Voc\u00EA n\u00E3o est\u00E1 autorizado a executar a a\u00E7\u00E3o {1} no recurso {0} +authorizer-not-defined=Nenhuma regra de resolu\u00E7\u00E3o de permiss\u00F5es foi definida. Para utilizar @{0} \u00E9 preciso definir a propriedade frameworkdemoiselle.security.authorizer.class como regra de resolu\u00E7\u00E3o de permiss\u00F5es desejada no arquivo demoiselle.properties. +user-not-authenticated=Usu\u00E1rio n\u00E3o autenticado +invalid-credentials=Usu\u00E1rio ou senha inv\u00E1lidos +has-role-verification=Verificando se o usu\u00E1rio {0} possui a(s) role(s)\: {1} +does-not-have-role=Usu\u00E1rio {0} n\u00E3o possui a(s) role(s)\: {1} +does-not-have-role-ui=Para acessar este recurso \u00E9 necess\u00E1rio ser {0} +user-has-role=Usu\u00E1rio {0} possui a(s) role(s)\: {1} + +authenticator-not-defined=Nenhum mecanismo de autentica\u00E7\u00E3o foi definido. Para utilizar {0} \u00E9 preciso definir a propriedade frameworkdemoiselle.security.authenticator.class como mecanismo de autentica\u00E7\u00E3o desejado no arquivo demoiselle.properties. + +management-notification-attribute-changed=O atributo [{0}] da classe gerenciada [{1}] foi alterado +management-null-class-defined=O controlador de gerenciamento informado n\u00E3o pode ser [null] +management-abstract-class-defined=O controlador de gerenciamento [{0}] precisa ser uma classe concreta +management-no-annotation-found=Classe {0} precisa ser anotada com @ManagementController +management-invalid-property-no-getter-setter=Falha ao inicializar classe gerenciada {0}, n\u00E3o foi encontrado um m\u00E9todo get ou m\u00E9todo set para a propriedade {1} +management-invalid-property-as-operation=Falha ao inicializar classe gerenciada {0}, n\u00E3o \u00E9 poss\u00EDvel declarar uma propriedade cujo m\u00E9todo get ou set \u00E9 uma opera\u00E7\u00E3o +management-introspection-error=Erro ao ler atributos da classe gerenciada {0} +management-type-not-found=A classe gerenciada informada n\u00E3o existe\: {0} +management-invoke-error=Erro ao tentar invocar a opera\u00E7\u00E3o "{0}" da classe gerenciada, a opera\u00E7\u00E3o n\u00E3o foi encontrada +management-write-value-error=N\u00E3o foi poss\u00EDvel definir um valor para a propriedade {0} +management-read-value-error=N\u00E3o foi poss\u00EDvel ler o valor da propriedade {0} +management-debug-acessing-property=Acessando propriedade {0} da classe gerenciada {1} +management-debug-setting-property=Definindo novo valor para propriedade {0} da classe gerenciada {1} +management-debug-invoking-operation=Invocando opera\u00E7\u00E3o {0} da classe gerenciada {1} +management-debug-starting-custom-context=Levantando contexto {0} para executar comando na classe gerenciada {1} +management-debug-stoping-custom-context=Desligando contexto {0} para classe gerenciada {1} +management-debug-registering-managed-type=Registrando classe gerenciada [{0}] +management-debug-processing-management-extension=Processando extens\u00E3o de gerenciamento [{0}] +management-debug-removing-management-extension=Desativando extens\u00E3o de gerenciamento [{0}] +management-validation-constraint-violation=Ocorreu um erro de valida\u00E7\u00E3o na classe [{0}] ao definir um valor para a propriedade [{1}]\: [{2}] +management-validation-validator-not-found=Nenhum provedor de valida\u00E7\u00E3o de beans encontrado, as anota\u00E7\u00F5es de valida\u00E7\u00E3o n\u00E3o ser\u00E3o processadas diff --git a/core/src/main/resources/demoiselle.properties b/core/src/main/resources/demoiselle.properties new file mode 100644 index 0000000..71ae24e --- /dev/null +++ b/core/src/main/resources/demoiselle.properties @@ -0,0 +1,5 @@ +# Enables JPA transaction strategy, automatically detected if demoiselle-jpa component is detected. Use only if you need to overwrite the default behaviour +#frameworkdemoiselle.transaction.class=br.gov.frameworkdemoiselle.transaction.JPATransaction + +# Enables JTA transaction strategy, automatically detected if demoiselle-jta component is detected. Use only if you need to overwrite the default behaviour +#frameworkdemoiselle.transaction.class=br.gov.frameworkdemoiselle.transaction.JTATransaction diff --git a/jwt/.gitignore b/jwt/.gitignore new file mode 100644 index 0000000..ddd6d6d --- /dev/null +++ b/jwt/.gitignore @@ -0,0 +1,3 @@ +/.settings/ +/.classpath +/.project diff --git a/jwt/pom.xml b/jwt/pom.xml new file mode 100644 index 0000000..cc69d6d --- /dev/null +++ b/jwt/pom.xml @@ -0,0 +1,33 @@ + + + 4.0.0 + org.demoiselle.jee + demoiselle-security-jwt + 3.0.0-SNAPSHOT + jar + + UTF-8 + 1.8 + 1.8 + + + + ${project.groupId} + demoiselle-core + ${project.version} + + + + ${project.groupId} + demoiselle-ws + ${project.version} + + + + ${project.groupId} + demoiselle-security + ${project.version} + + + + diff --git a/pom.xml b/pom.xml index 0b6ab23..3e46af3 100644 --- a/pom.xml +++ b/pom.xml @@ -23,7 +23,8 @@ persistence ws - + security + basic diff --git a/security/src/main/java/org/demoiselle/jee/security/AfterLoginSuccessful.java b/security/src/main/java/org/demoiselle/jee/security/AfterLoginSuccessful.java deleted file mode 100644 index 34ad89f..0000000 --- a/security/src/main/java/org/demoiselle/jee/security/AfterLoginSuccessful.java +++ /dev/null @@ -1,50 +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 org.demoiselle.jee.security; - -import java.io.Serializable; - -/** - *

- * This interface represents an event that is fired when user successfully logs in. - *

- * - * @author SERPRO - */ -public interface AfterLoginSuccessful extends Serializable { - -} diff --git a/security/src/main/java/org/demoiselle/jee/security/AfterLogoutSuccessful.java b/security/src/main/java/org/demoiselle/jee/security/AfterLogoutSuccessful.java deleted file mode 100644 index 52ca947..0000000 --- a/security/src/main/java/org/demoiselle/jee/security/AfterLogoutSuccessful.java +++ /dev/null @@ -1,50 +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 org.demoiselle.jee.security; - -import java.io.Serializable; - -/** - *

- * This interface represents an event fired just after the user unauthenticates. - *

- * - * @author SERPRO - */ -public interface AfterLogoutSuccessful extends Serializable { - -} diff --git a/security/src/main/java/org/demoiselle/jee/security/Authenticator.java b/security/src/main/java/org/demoiselle/jee/security/Authenticator.java deleted file mode 100644 index 52d3d70..0000000 --- a/security/src/main/java/org/demoiselle/jee/security/Authenticator.java +++ /dev/null @@ -1,89 +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 org.demoiselle.jee.security; - -import java.io.Serializable; -import java.security.Principal; - -/** - *

- * Defines the methods that should be implemented by anyone who wants an authentication mechanism. - *

- * - * @author SERPRO - */ -public interface Authenticator extends Serializable { - - /** - *

- * Executes the necessary steps to authenticate an user. After this call, {@link #getUser()} must return - * the currently authenticated user, or null if the authentication process fails. - *

- * - * @throws InvalidCredentialsException - * You should throw this exception when the informed credentials are invalid. - * - * @throws Exception - * If the underlying authentication mechanism throwns any other exception, - * just throw it and leave the security context implementation to handle it. - */ - void authenticate() throws Exception; - - /** - *

- * Executes the necessary steps to unauthenticate an user. After this call, {@link #getUser()} must return null. - *

- * - * @throws Exception - * If the underlying authentication mechanism throwns any other exception, - * just throw it and leave the security context implementation to handle it. - */ - void unauthenticate() throws Exception; - - /** - *

- * Returns the currently authenticated user. - *

- * - * @return the user currently authenticated, or null if there is no - * authenticated user. - * - * @see #authenticate() - * @see #unauthenticate() - */ - Principal getUser(); -} diff --git a/security/src/main/java/org/demoiselle/jee/security/Authorizer.java b/security/src/main/java/org/demoiselle/jee/security/Authorizer.java deleted file mode 100644 index 04ca98b..0000000 --- a/security/src/main/java/org/demoiselle/jee/security/Authorizer.java +++ /dev/null @@ -1,75 +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 org.demoiselle.jee.security; - -import java.io.Serializable; - -/** - *

- * Defines the methods that should be implemented by anyone who wants an authorization mechanism. - *

- * - * @author SERPRO - */ -public interface Authorizer extends Serializable { - - /** - *

- * Checks if the logged user has a specific role. - *

- * - * @param role role to be checked. - * @return {@code true} if the user has the role. - * @throws Exception if the underlying permission checking mechanism throwns any other exception, - * just throw it and leave the security context implementation to handle it. - */ - boolean hasRole(String role) throws Exception; - - /** - *

- * Checks if the logged user has permission to execute a specific operation on a specific resource. - *

- * - * @param resource resource to be checked. - * @param operation operation to be checked. - * @return {@code true} if the user has the permission. - * @throws Exception if the underlying permission checking mechanism throwns any other exception, - * just throw it and leave the security context implementation to handle it. - */ - boolean hasPermission(String resource, String operation) throws Exception; - -} diff --git a/security/src/main/java/org/demoiselle/jee/security/JaxRsFilter.java b/security/src/main/java/org/demoiselle/jee/security/JaxRsFilter.java new file mode 100644 index 0000000..22e86c5 --- /dev/null +++ b/security/src/main/java/org/demoiselle/jee/security/JaxRsFilter.java @@ -0,0 +1,61 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.demoiselle.jee.security; + +import java.util.logging.Logger; +import javax.annotation.PostConstruct; +import javax.inject.Inject; +import javax.ws.rs.client.ClientRequestContext; +import javax.ws.rs.client.ClientRequestFilter; +import javax.ws.rs.client.ClientResponseContext; +import javax.ws.rs.client.ClientResponseFilter; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerRequestFilter; +import javax.ws.rs.container.ContainerResponseContext; +import javax.ws.rs.container.ContainerResponseFilter; +import javax.ws.rs.container.PreMatching; +import javax.ws.rs.ext.Provider; + +/** + * + * @author 70744416353 + */ +@Provider +@PreMatching +public class JaxRsFilter implements ClientRequestFilter, ClientResponseFilter, ContainerRequestFilter, ContainerResponseFilter { + + @Inject + private Logger LOG; + + @Inject + private SecurityContext securityContext; + + @Override + public void filter(ClientRequestContext requestContext) { + String token = requestContext.getHeaders().get("Authorization").toString(); + if (!token.isEmpty()) { + securityContext.setToken(token); + } + } + + @Override + public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) { + } + + @Override + public void filter(ContainerRequestContext requestContext) { + } + + @Override + public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) { + responseContext.getHeaders().putSingle("Authorization", "Basic"); + } + + @PostConstruct + public void init() { + LOG.info("Demoiselle Module - Security"); + } +} diff --git a/security/src/main/java/org/demoiselle/jee/security/SecurityContext.java b/security/src/main/java/org/demoiselle/jee/security/SecurityContext.java index ae146d3..29e3760 100644 --- a/security/src/main/java/org/demoiselle/jee/security/SecurityContext.java +++ b/security/src/main/java/org/demoiselle/jee/security/SecurityContext.java @@ -38,6 +38,10 @@ package org.demoiselle.jee.security; import java.io.Serializable; import java.security.Principal; +import java.util.Map; +import java.util.Set; +import org.demoiselle.jee.security.exception.AuthorizationException; +import org.demoiselle.jee.security.exception.NotLoggedInException; /** *

@@ -48,72 +52,65 @@ import java.security.Principal; */ public interface SecurityContext extends Serializable { - /** - * Executes the login of a user to the application. - * - * @throws AuthenticationException - * When the logon process fails, this exception is thrown. - * @throws InvalidCredentialsException - * When the user's credentials coudn't be validated. InvalidCredentialsException is a special case of - * AuthenticationException. - */ - void login(); + /** + * Checks if a specific user is logged in. + * + * @return {@code true} if the user is logged in + */ + boolean isLoggedIn(); - /** - * Executes the logout of a user. - * - * @throws AuthenticationException - * When the logout process fails, this exception is thrown. - */ - void logout(); + /** + * @throws NotLoggedInException if there is no user logged in a specific + * session + */ + void checkLoggedIn(); - /** - * Checks if a specific user is logged in. - * - * @return {@code true} if the user is logged in - */ - boolean isLoggedIn(); + /** + * Checks if the logged user has permission to execute an specific operation + * on a specific resource. + * + * @param resource resource to be checked + * @param operation operation to be checked + * @return {@code true} if the user has the permission + * @throws AuthorizationException When the permission checking fails, this + * exception is thrown. + * @throws NotLoggedInException if there is no user logged in a specific + * session. + */ + boolean hasPermission(String resource, String operation); - /** - * @throws NotLoggedInException - * if there is no user logged in a specific session - */ - void checkLoggedIn(); + /** + * Checks if the logged user has an specific role + * + * @param role role to be checked + * @return {@code true} if the user has the role + * @throws AuthorizationException When the permission checking fails, this + * exception is thrown. + * @throws NotLoggedInException if there is no user logged in a specific + * session. + */ + boolean hasRole(String role); - /** - * Checks if the logged user has permission to execute an specific operation on a specific resource. - * - * @param resource - * resource to be checked - * @param operation - * operation to be checked - * @return {@code true} if the user has the permission - * @throws AuthorizationException - * When the permission checking fails, this exception is thrown. - * @throws NotLoggedInException - * if there is no user logged in a specific session. - */ - boolean hasPermission(String resource, String operation); + /** + * Return the user logged in the session. + * + * @return the user logged in a specific authenticated session. If there is + * no active session {@code null} is returned. + */ + Principal getUser(); - /** - * Checks if the logged user has an specific role - * - * @param role - * role to be checked - * @return {@code true} if the user has the role - * @throws AuthorizationException - * When the permission checking fails, this exception is thrown. - * @throws NotLoggedInException - * if there is no user logged in a specific session. - */ - boolean hasRole(String role); + void setUser(Principal principal); - /** - * Return the user logged in the session. - * - * @return the user logged in a specific authenticated session. If there is no active session {@code null} is - * returned. - */ - Principal getUser(); + String getToken(); + + void setToken(String token); + + void setRoles(Set roles); + + void setPermission(Map permissions); + + Set getResources(String operation); + + Set getOperations(String resources); } diff --git a/security/src/main/java/org/demoiselle/jee/security/TokensManager.java b/security/src/main/java/org/demoiselle/jee/security/TokensManager.java new file mode 100644 index 0000000..27e7e6c --- /dev/null +++ b/security/src/main/java/org/demoiselle/jee/security/TokensManager.java @@ -0,0 +1,63 @@ +/* + * 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 org.demoiselle.jee.security; + +import java.io.Serializable; +import java.security.Principal; +import java.util.Map; +import java.util.Set; +import org.demoiselle.jee.security.exception.AuthorizationException; +import org.demoiselle.jee.security.exception.NotLoggedInException; + +/** + *

+ * Structure used to handle both authentication and authorizations mechanisms. + *

+ * + * @author SERPRO + */ +public interface TokensManager extends Serializable { + + Principal getUser(String token); + + String create(Principal user); + + void remove(String token); + + boolean validate(String token); + +} diff --git a/security/src/main/java/org/demoiselle/jee/security/impl/SecurityContextImpl.java b/security/src/main/java/org/demoiselle/jee/security/impl/SecurityContextImpl.java deleted file mode 100644 index ac656cd..0000000 --- a/security/src/main/java/org/demoiselle/jee/security/impl/SecurityContextImpl.java +++ /dev/null @@ -1,231 +0,0 @@ -package org.demoiselle.jee.security.impl; - -import javax.enterprise.context.Dependent; -import javax.enterprise.inject.spi.CDI; -import javax.inject.Named; -import java.io.Serializable; -import java.security.Principal; -import org.demoiselle.jee.core.annotation.literal.NameQualifier; -import org.demoiselle.jee.core.annotation.literal.StrategyQualifier; -import org.demoiselle.jee.core.exception.DemoiselleException; -import org.demoiselle.jee.core.util.ResourceBundle; -import org.demoiselle.jee.security.AfterLoginSuccessful; -import org.demoiselle.jee.security.AfterLogoutSuccessful; -import org.demoiselle.jee.security.Authenticator; -import org.demoiselle.jee.security.Authorizer; -import org.demoiselle.jee.security.SecurityContext; -import org.demoiselle.jee.security.exception.AuthenticationException; -import org.demoiselle.jee.security.exception.AuthorizationException; -import org.demoiselle.jee.security.exception.NotLoggedInException; - -/** - *

- * This is the default implementation of {@link SecurityContext} interface. - *

- * - * @author SERPRO - */ -@Dependent -@Named("securityContext") -public class SecurityContextImpl implements SecurityContext { - - private static final long serialVersionUID = 1L; - - private transient ResourceBundle bundle; - - private Authenticator authenticator; - - private Authorizer authorizer; - - private Authenticator getAuthenticator() { - if (this.authenticator == null) { - Class type = getConfig().getAuthenticatorClass(); - - if (type != null) { - this.authenticator = CDI.current().select(type).get(); //Beans.getReference(type); - } else { - this.authenticator = CDI.current().select(Authenticator.class, new StrategyQualifier()).get(); // Beans.getReference(Authenticator.class, new StrategyQualifier()); - } - } - - return this.authenticator; - } - - private Authorizer getAuthorizer() { - if (this.authorizer == null) { - Class type = getConfig().getAuthorizerClass(); - - if (type != null) { - this.authorizer = CDI.current().select(type).get(); //Beans.getReference(type); - } else { - this.authorizer = CDI.current().select(Authorizer.class, new StrategyQualifier()).get(); //Beans.getReference(Authorizer.class, new StrategyQualifier()); - } - } - - return this.authorizer; - } - - /** - * @see org.demoiselle.security.SecurityContext#hasPermission(String, - * String) - */ - @Override - public boolean hasPermission(String resource, String operation) { - boolean result = true; - - if (getConfig().isEnabled()) { - checkLoggedIn(); - - try { - result = getAuthorizer().hasPermission(resource, operation); - - } catch (DemoiselleException cause) { - throw cause; - - } catch (Exception cause) { - throw new AuthorizationException(cause); - } - } - - return result; - } - - /** - * @see org.demoiselle.security.SecurityContext#hasRole(String) - */ - @Override - public boolean hasRole(String role) { - boolean result = true; - - if (getConfig().isEnabled()) { - checkLoggedIn(); - - try { - result = getAuthorizer().hasRole(role); - - } catch (DemoiselleException cause) { - throw cause; - - } catch (Exception cause) { - throw new AuthorizationException(cause); - } - } - - return result; - } - - /** - * @see org.demoiselle.security.SecurityContext#isLoggedIn() - */ - @Override - public boolean isLoggedIn() { - boolean result = true; - - if (getConfig().isEnabled()) { - result = getUser() != null; - } - - return result; - } - - /** - * @see org.demoiselle.security.SecurityContext#login() - */ - @Override - public void login() { - if (getConfig().isEnabled()) { - - try { - getAuthenticator().authenticate(); - - } catch (DemoiselleException cause) { - throw cause; - - } catch (Exception cause) { - throw new AuthenticationException(cause); - } - - CDI.current().getBeanManager().fireEvent(new AfterLoginSuccessful() { - - private static final long serialVersionUID = 1L; - }); -// Beans.getBeanManager().fireEvent(new AfterLoginSuccessful() { -// -// private static final long serialVersionUID = 1L; -// }); - } - } - - /** - * @see org.demoiselle.security.SecurityContext#logout() - */ - @Override - public void logout() throws NotLoggedInException { - if (getConfig().isEnabled()) { - checkLoggedIn(); - - try { - getAuthenticator().unauthenticate(); - - } catch (DemoiselleException cause) { - throw cause; - - } catch (Exception cause) { - throw new AuthenticationException(cause); - } - - CDI.current().getBeanManager().fireEvent(new AfterLogoutSuccessful() { - - private static final long serialVersionUID = 1L; - }); -// Beans.getBeanManager().fireEvent(new AfterLogoutSuccessful() { -// -// private static final long serialVersionUID = 1L; -// }); - } - } - - /** - * @see org.demoiselle.security.SecurityContext#getUser() - */ - @Override - public Principal getUser() { - Principal user = getAuthenticator().getUser(); - - if (!getConfig().isEnabled() && user == null) { - user = new EmptyUser(); - } - - return user; - } - - private SecurityConfig getConfig() { - return CDI.current().select(SecurityConfig.class).get(); -// return Beans.getReference(SecurityConfig.class); - } - - public void checkLoggedIn() throws NotLoggedInException { - if (!isLoggedIn()) { - throw new NotLoggedInException(getBundle().getString("user-not-authenticated")); - } - } - - private ResourceBundle getBundle() { - if (bundle == null) { - bundle = CDI.current().select(ResourceBundle.class, new NameQualifier("demoiselle-core-bundle")).get(); -// bundle = Beans.getReference(ResourceBundle.class, new NameQualifier("demoiselle-core-bundle")); - } - - return bundle; - } - - private static class EmptyUser implements Principal, Serializable { - - private static final long serialVersionUID = 1L; - - @Override - public String getName() { - return "demoiselle"; - } - } -} diff --git a/security/src/main/java/org/demoiselle/jee/security/interceptor/LoggedInInterceptor.java b/security/src/main/java/org/demoiselle/jee/security/interceptor/LoggedInInterceptor.java index 7f26c67..f812900 100644 --- a/security/src/main/java/org/demoiselle/jee/security/interceptor/LoggedInInterceptor.java +++ b/security/src/main/java/org/demoiselle/jee/security/interceptor/LoggedInInterceptor.java @@ -34,7 +34,6 @@ * ou escreva para a Fundação do Software Livre (FSF) Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. */ - package org.demoiselle.jee.security.interceptor; import javax.annotation.Priority; @@ -48,16 +47,15 @@ import org.demoiselle.jee.security.SecurityContext; /** *

- *Intercepts calls with {@link LoggedIn} annotations. + * Intercepts calls with {@link LoggedIn} annotations. *

* * @author SERPRO */ - @LoggedIn @Interceptor @Priority(Interceptor.Priority.APPLICATION) -public class LoggedInInterceptor implements Serializable{ +public class LoggedInInterceptor implements Serializable { private static final long serialVersionUID = 1L; diff --git a/security/src/main/java/org/demoiselle/jee/security/interceptor/RequiredPermissionInterceptor.java b/security/src/main/java/org/demoiselle/jee/security/interceptor/RequiredPermissionInterceptor.java index 98364e8..6d33ecd 100644 --- a/security/src/main/java/org/demoiselle/jee/security/interceptor/RequiredPermissionInterceptor.java +++ b/security/src/main/java/org/demoiselle/jee/security/interceptor/RequiredPermissionInterceptor.java @@ -140,6 +140,5 @@ public class RequiredPermissionInterceptor implements Serializable { private SecurityContext getSecurityContext() { return CDI.current().select(SecurityContext.class).get(); -// return Beans.getReference(SecurityContext.class); } } diff --git a/security/src/main/java/org/demoiselle/jee/security/interceptor/RequiredRoleInterceptor.java b/security/src/main/java/org/demoiselle/jee/security/interceptor/RequiredRoleInterceptor.java index e4d7a34..4a07df6 100644 --- a/security/src/main/java/org/demoiselle/jee/security/interceptor/RequiredRoleInterceptor.java +++ b/security/src/main/java/org/demoiselle/jee/security/interceptor/RequiredRoleInterceptor.java @@ -106,7 +106,6 @@ public class RequiredRoleInterceptor implements Serializable { private SecurityContext getSecurityContext() { return CDI.current().select(SecurityContext.class).get(); -// return Beans.getReference(SecurityContext.class); } } diff --git a/security/src/main/resources/demoiselle-security-bundle.properties b/security/src/main/resources/demoiselle-security-bundle.properties new file mode 100644 index 0000000..eb15108 --- /dev/null +++ b/security/src/main/resources/demoiselle-security-bundle.properties @@ -0,0 +1,130 @@ +# 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 \u00E9 parte do Framework Demoiselle. +# +# O Framework Demoiselle \u00E9 um software livre; voc\u00EA pode redistribu\u00ED-lo e/ou +# modific\u00E1-lo dentro dos termos da GNU LGPL vers\u00E3o 3 como publicada pela Funda\u00E7\u00E3o +# do Software Livre (FSF). +# +# Este programa \u00E9 distribu\u00EDdo na esperan\u00E7a que possa ser \u00FAtil, mas SEM NENHUMA +# GARANTIA; sem uma garantia impl\u00EDcita de ADEQUA\u00C7\u00C3O a qualquer MERCADO ou +# APLICA\u00C7\u00C3O EM PARTICULAR. Veja a Licen\u00E7a P\u00FAblica Geral GNU/LGPL em portugu\u00EAs +# para maiores detalhes. +# +# Voc\u00EA deve ter recebido uma c\u00F3pia da GNU LGPL vers\u00E3o 3, sob o t\u00EDtulo +# "LICENCA.txt", junto com esse programa. Se n\u00E3o, acesse +# ou escreva para a Funda\u00E7\u00E3o do Software Livre (FSF) Inc., +# 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. + +version=${project.version} +engine-on=Iniciando o Demoiselle Framework ${project.version} (Neo) +resource-not-found=Arquivo {0} n\u00E3o foi encontrado +key-not-found=A chave {0} n\u00E3o foi encontrada +ambiguous-strategy-resolution=Foi detectada ambiguidade da interface {0} com as seguintes implementa\u00E7\u00F5es\: {1}. Para resolver o conflito, defina explicitamente a implementa\u00E7\u00E3o no demoiselle.properties. +ambiguous-bean-resolution=Falha ao obter {0} pois foi detectada ambiguidade nas seguintes implementa\u00E7\u00F5es\: {1} +bean-not-found=Voc\u00EA est\u00E1 tentando obter um objeto n\u00E3o reconhecido pelo CDI via Beans.getReference({0}) +store-not-found=O objeto do tipo [{0}] n\u00E3o pode ser armazenado no escopo indicado\: {1} +more-than-one-exceptionhandler-defined-for-same-class=Foi definido mais de um m\u00E9todo na classe {0} para tratar a exce\u00E7\u00E3o {1} +handling-exception=Tratando a exce\u00E7\u00E3o {0} +taking-off=O Demoiselle ${project.version} decolou +engine-off=Desligando os motores do Demoiselle ${project.version} +setting-up-bean-manager=BeanManager dispon\u00EDvel atrav\u00E9s do utilit\u00E1rio {0} + +user-transaction-lookup-fail=N\u00E3o foi encontrada nenhuma transa\u00E7\u00E3o com o nome {0} no contexto JNDI +transactional-execution=Execu\u00E7\u00E3o transacional de {0} +begin-transaction=Transa\u00E7\u00E3o iniciada +transaction-marked-rollback=Transa\u00E7\u00E3o marcada para rollback [{0}] +transaction-already-finalized=A transa\u00E7\u00E3o j\u00E1 havia sido finalizada +transaction-commited=Transa\u00E7\u00E3o finalizada com sucesso +transaction-rolledback=Transa\u00E7\u00E3o finalizada com rollback + +bootstrap.configuration.processing=Processando {0} +bootstrap-context-already-managed=O contexto {0} para o escopo {1} j\u00E1 foi adicionado +bootstrap-context-added=Adicionando o contexto {0} para o escopo {1} + +loading-configuration-class=Carregando a classe de configura\u00E7\u00E3o {0} +configuration-field-loaded={0}: {2} +configuration-attribute-is-mandatory=A configura\u00E7\u00E3o {0} \u00E9 obrigat\u00F3ria, mas n\u00E3o foi encontrada em {1} +configuration-name-attribute-cant-be-empty=A nota\u00E7\u00E3o @Name n\u00E3o pode estar em branco +configuration-generic-extraction-error=Ocorreu um erro durante a extra\u00E7\u00E3o do tipo {0} com o extrator {1} +configuration-dot-after-prefix=N\u00E3o \u00E9 necess\u00E1rio adicionar o ponto ap\u00F3s o prefixo para uma classe de configura\u00E7\u00E3o. \u00C9 recomendado que sejam retirados, pois poder\u00E3o causar erros em vers\u00F5es futuras do Framework. +configuration-key-not-found={0}\: [n\u00E3o encontrada] +configuration-extractor-not-found=N\u00E3o foi poss\u00EDvel encontrar a classe extratora para o atributo {0}. Implemente a interface {1} para criar sua classe extratora. +configuration-not-conversion=N\u00E3o \u00E9 poss\u00EDvel converter o valor {0} para o tipo {1} + +transaction-not-defined=Nenhuma transa\u00E7\u00E3o foi definida. Para utilizar @{0} \u00E9 preciso definir a propriedade frameworkdemoiselle.transaction.class com a estrat\u00E9gia de transa\u00E7\u00E3o desejada no arquivo demoiselle.properties +executing-all=Executando m\u00E9todos anotados com @{0} +custom-context-selected=Produzindo inst\u00E2ncia do contexto {0} +custom-context-was-activated=O contexto {0} foi ativado para o escopo {1} +custom-context-was-deactivated=O contexto {0} foi desativado para o escopo {1} +custom-context-already-activated=N\u00E3o foi poss\u00EDvel ativar o contexto {0}, o escopo {1} j\u00E1 est\u00E1 ativo no contexto {2} +custom-context-not-found=N\u00E3o foi encontrado um contexto gerenciado do tipo [{0}] para o escopo [{1}] +custom-context-manager-not-initialized=ContextManager n\u00E3o foi inicializado. Chame [initialize] ao capturar o evento [AfterBeanDiscovery] em uma extens\u00E3o CDI + +error-creating-new-instance-for=Error creating a new instance for "{0}" +executed-successfully={0} execultado com sucesso +must-declare-one-single-parameter=Voc\u00EA deve declarar um par\u00E2metro \u00FAnico em {0} +loading-default-transaction-manager=Carregando o gerenciador de transa\u00E7\u00E3o padr\u00E3o {0} +results-count-greater-page-size=Quantidade de resultados {0} \u00E9 maior que o tamanho da p\u00E1gina {1} +page-result=Resultado paginado [p\u00E1gina\={0}, total de resultados\={1}] +pagination-not-initialized=Pagina\u00E7\u00E3o n\u00E3o inicializada. Inicialize o sistema de pagina\u00E7\u00E3o definindo a p\u00E1gina atual ou o total de resultados ao menos uma vez na requisi\u00E7\u00E3o. +pagination-invalid-value=Valor inv\u00E1lido para paginador: [{0}]. +page=P\u00E1gina [n\u00FAmero\={0}, tamanho\={1}] +processing=Processando\: {0} +processing-fail=Falha no processamento devido a uma exce\u00E7\u00E3o lan\u00E7ada pela aplica\u00E7\u00E3o +for= \ para\: +file-not-found=O arquivo {0} n\u00E3o foi encontrado + +adding-message-to-context=Adicionando uma mensagem no contexto: [{0}] +access-checking=Verificando permiss\u00E3o do usu\u00E1rio {0} para executar a a\u00E7\u00E3o {1} no recurso {2} +access-allowed=O usu\u00E1rio {0} acessou o recurso {2} com a a\u00E7\u00E3o {1} +access-denied=O usu\u00E1rio {0} n\u00E3o possui permiss\u00E3o para executar a a\u00E7\u00E3o {1} no recurso {2} +access-denied-ui=Voc\u00EA n\u00E3o est\u00E1 autorizado a executar a a\u00E7\u00E3o {1} no recurso {0} +authorizer-not-defined=Nenhuma regra de resolu\u00E7\u00E3o de permiss\u00F5es foi definida. Para utilizar @{0} \u00E9 preciso definir a propriedade frameworkdemoiselle.security.authorizer.class como regra de resolu\u00E7\u00E3o de permiss\u00F5es desejada no arquivo demoiselle.properties. +user-not-authenticated=Usu\u00E1rio n\u00E3o autenticado +invalid-credentials=Usu\u00E1rio ou senha inv\u00E1lidos +has-role-verification=Verificando se o usu\u00E1rio {0} possui a(s) role(s)\: {1} +does-not-have-role=Usu\u00E1rio {0} n\u00E3o possui a(s) role(s)\: {1} +does-not-have-role-ui=Para acessar este recurso \u00E9 necess\u00E1rio ser {0} +user-has-role=Usu\u00E1rio {0} possui a(s) role(s)\: {1} + +authenticator-not-defined=Nenhum mecanismo de autentica\u00E7\u00E3o foi definido. Para utilizar {0} \u00E9 preciso definir a propriedade frameworkdemoiselle.security.authenticator.class como mecanismo de autentica\u00E7\u00E3o desejado no arquivo demoiselle.properties. + +management-notification-attribute-changed=O atributo [{0}] da classe gerenciada [{1}] foi alterado +management-null-class-defined=O controlador de gerenciamento informado n\u00E3o pode ser [null] +management-abstract-class-defined=O controlador de gerenciamento [{0}] precisa ser uma classe concreta +management-no-annotation-found=Classe {0} precisa ser anotada com @ManagementController +management-invalid-property-no-getter-setter=Falha ao inicializar classe gerenciada {0}, n\u00E3o foi encontrado um m\u00E9todo get ou m\u00E9todo set para a propriedade {1} +management-invalid-property-as-operation=Falha ao inicializar classe gerenciada {0}, n\u00E3o \u00E9 poss\u00EDvel declarar uma propriedade cujo m\u00E9todo get ou set \u00E9 uma opera\u00E7\u00E3o +management-introspection-error=Erro ao ler atributos da classe gerenciada {0} +management-type-not-found=A classe gerenciada informada n\u00E3o existe\: {0} +management-invoke-error=Erro ao tentar invocar a opera\u00E7\u00E3o "{0}" da classe gerenciada, a opera\u00E7\u00E3o n\u00E3o foi encontrada +management-write-value-error=N\u00E3o foi poss\u00EDvel definir um valor para a propriedade {0} +management-read-value-error=N\u00E3o foi poss\u00EDvel ler o valor da propriedade {0} +management-debug-acessing-property=Acessando propriedade {0} da classe gerenciada {1} +management-debug-setting-property=Definindo novo valor para propriedade {0} da classe gerenciada {1} +management-debug-invoking-operation=Invocando opera\u00E7\u00E3o {0} da classe gerenciada {1} +management-debug-starting-custom-context=Levantando contexto {0} para executar comando na classe gerenciada {1} +management-debug-stoping-custom-context=Desligando contexto {0} para classe gerenciada {1} +management-debug-registering-managed-type=Registrando classe gerenciada [{0}] +management-debug-processing-management-extension=Processando extens\u00E3o de gerenciamento [{0}] +management-debug-removing-management-extension=Desativando extens\u00E3o de gerenciamento [{0}] +management-validation-constraint-violation=Ocorreu um erro de valida\u00E7\u00E3o na classe [{0}] ao definir um valor para a propriedade [{1}]\: [{2}] +management-validation-validator-not-found=Nenhum provedor de valida\u00E7\u00E3o de beans encontrado, as anota\u00E7\u00F5es de valida\u00E7\u00E3o n\u00E3o ser\u00E3o processadas diff --git a/security/src/main/resources/demoiselle.properties b/security/src/main/resources/demoiselle.properties new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/security/src/main/resources/demoiselle.properties diff --git a/ws/src/main/java/org/demoiselle/jee/ws/JaxRsFilter.java b/ws/src/main/java/org/demoiselle/jee/ws/JaxRsFilter.java index e7f43dc..951561a 100644 --- a/ws/src/main/java/org/demoiselle/jee/ws/JaxRsFilter.java +++ b/ws/src/main/java/org/demoiselle/jee/ws/JaxRsFilter.java @@ -44,11 +44,9 @@ public class JaxRsFilter implements ClientRequestFilter, ClientResponseFilter, C @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext response) { - - response.getHeaders().putSingle("Access-Control-Allow-Origin", "*"); - response.getHeaders().putSingle("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, DELETE"); - response.getHeaders().putSingle("Access-Control-Allow-Headers", "Content-Type"); - + response.getHeaders().putSingle("Access-Control-Allow-Origin", "*"); + response.getHeaders().putSingle("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, DELETE"); + response.getHeaders().putSingle("Access-Control-Allow-Headers", "Content-Type"); } @PostConstruct -- libgit2 0.21.2