Skip to content

Instantly share code, notes, and snippets.

@sidneydemoraes
Created April 27, 2017 21:01
Show Gist options
  • Save sidneydemoraes/ff2e583a1f023aca7bb3b392e0c72d8b to your computer and use it in GitHub Desktop.
Save sidneydemoraes/ff2e583a1f023aca7bb3b392e0c72d8b to your computer and use it in GitHub Desktop.
TechTalk - Gradle + Spring Boot + Groovy - Autenticador Spring Security
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