Boa tarde. Estou trabalhando em um projeto contendo Spring Boot + App Engine + Hibernate. O controle de acesso está sendo feito via Autenticação Básica, onde tenho as seguintes classes de configuração e controles:
Classe configuração
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier("userDetailsService")
private UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("_ah/**").permitAll()
.antMatchers(HttpMethod.OPTIONS).permitAll()
.anyRequest().authenticated()
.and().httpBasic()
.and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
}
Classe Usuario
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.hibernate.annotations.Type;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@Entity
@Table(name = "Usuario")
@TableGenerator(name = "USUARIO_IDS",
table = "TABELA_DE_IDS",
pkColumnName = "TABELA",
pkColumnValue = "USUARIO",
valueColumnName = "ID_ATUAL",
allocationSize = 10
)
public class Usuario implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "USUARIO_IDS")
private Long id;
private String nome;
private String email;
private String telefone;
@OneToOne
@JoinColumn(name = "perfil_id")
private Perfil perfil;
@Type(type = "true_false")
private boolean status;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public Perfil getPerfil() {
return perfil;
}
public void setPerfil(Perfil perfil) {
this.perfil = perfil;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
@JsonIgnore
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<GrantedAuthority> auths = new ArrayList<>();
auths.add((new SimpleGrantedAuthority((this.perfil.getNome()))));
return auths;
}
@JsonIgnore
@Override
public String getPassword() {
return "{noop}";
}
@JsonIgnore
@Override
public String getUsername() {
return this.email;
}
@JsonIgnore
@Override
public boolean isAccountNonExpired() {
return true;
}
@JsonIgnore
@Override
public boolean isAccountNonLocked() {
return true;
}
@JsonIgnore
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@JsonIgnore
@Override
public boolean isEnabled() {
return this.status;
}
@Override
public String toString() {
return "Usuario{" +
"id=" + id +
", nome='" + nome + "' " +
", email='" + email + "' " +
", telefone='" + telefone + "' " +
", perfil=" + perfil +
", status=" + status +
'}';
}
}
Classe UserService
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service("userDetailsService")
public class UsuarioService implements UserDetailsService {
@Autowired
private UsuarioDao usuarioDao;
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
Usuario usuario = usuarioDao.buscaPorEmail(email);
if (usuario != null)
return usuario;
return null;
}
}
Classe LoginController
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
@RestController
@CrossOrigin
@RequestMapping(path = "/login")
public class LoginController {
@Autowired
private UsuarioDao usuarioDao;
@PreAuthorize("hasAnyAuthority('ESPECIALISTA','GERENTE','ADMIN')")
@PostMapping
public ResponseEntity<Usuario> logar(@RequestBody Usuario usuario) {
Usuario usuarioEncontrado = usuarioDao.buscaPorEmail(usuario.getEmail());
if (usuarioEncontrado != null)
return new ResponseEntity<Usuario>(usuarioEncontrado, HttpStatus.OK);
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
Eu gostaria de entender como implementar um Login via Google na aplicação e depois de obtido a autenticação, manter as regras de autorização, como exemplo da classe LoginController: @PreAuthorize("hasAnyAuthority('ESPECIALISTA','GERENTE','ADMIN')")
O projeto de back e front estão separados.
Estou lendo alguns artigos mas ainda não consegui ter sucesso. Até o momento, consegui executar em um projeto teste, o que é descrito neste link: https://dzone.com/articles/getting-started-with-google-sign-in-in-spring-boot Aqui ele mostra uma forma de autenticar mas não como aplicar as roles
Alguém poderia me dar um norte?
Obrigado.