Created
April 27, 2017 21:01
-
-
Save sidneydemoraes/ff2e583a1f023aca7bb3b392e0c72d8b to your computer and use it in GitHub Desktop.
TechTalk - Gradle + Spring Boot + Groovy - Autenticador Spring Security
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import br.com.smc.meurumo.domain.seguranca.repository.UsuarioRepository | |
import org.slf4j.LoggerFactory | |
import org.springframework.beans.factory.annotation.Autowired | |
import org.springframework.security.authentication.AuthenticationProvider | |
import org.springframework.security.authentication.BadCredentialsException | |
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken | |
import org.springframework.security.core.Authentication | |
import org.springframework.security.core.AuthenticationException | |
import org.springframework.security.core.authority.SimpleGrantedAuthority | |
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder | |
import org.springframework.stereotype.Component | |
/** | |
* Provedor de autenticação para o Spring Security | |
*/ | |
@Component | |
class ProvedorAutenticacao implements AuthenticationProvider { | |
@Override | |
Authentication authenticate(Authentication authentication) throws AuthenticationException { | |
def email = "${authentication.principal}" | |
log.info("Iniciando autenticacao do usuario ${email}.") | |
def senha = "${authentication.credentials}" | |
def usuario = repo.findByEmail(email) | |
if (!usuario) { | |
log.info("Usuario ${email} nao encontrado na base de dados.") | |
throw new BadCredentialsException("Login e/ou Senha invalidos.") | |
} | |
def senhaProtegida = usuario.senha | |
if (!protetor.matches(senha, senhaProtegida)) { | |
log.debug("Senha não confere.") | |
throw new BadCredentialsException("Login e/ou Senha invalidos.") | |
} | |
if (usuario.ativo) { | |
def authorities = [] | |
usuario.with { | |
log.info("Usuario ${email} localizado e autenticado.") | |
perfis.each { | |
authorities.add(new SimpleGrantedAuthority("${it}")) | |
} | |
} | |
return new UsernamePasswordAuthenticationToken(email, senhaProtegida, authorities) | |
} | |
log.info("Usuario ${email} localizado mas inativo.") | |
throw new BadCredentialsException("Este usuario esta desativado."); | |
} | |
@Override | |
boolean supports(Class<?> authentication) { | |
return authentication.equals(UsernamePasswordAuthenticationToken.class) | |
} | |
/* Servicos injetados */ | |
@Autowired | |
UsuarioRepository repo | |
@Autowired | |
BCryptPasswordEncoder protetor | |
/* Outros componentes */ | |
private def log = LoggerFactory.getLogger(ProvedorAutenticacao.class) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment