Realizei a implementação conforme as aulas, ja revisei e não identifiquei o que está ocorrendo. Após realizar o login através da url: http://localhost:9090/casadocodigo/produtos/form, apresenta http status 403 - acesso negado. Os dados do usuário estão corretos, a permissão esta ROLE_ADMIN na base de dados, e a classe responsável também encontra-se correta. As urls que estão com permitAll(), esta fucionando normalmente.
Segue as classes:
package br.com.casadocodigo.loja.conf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import br.com.casadocodigo.loja.Daos.UsuarioDAO;
@EnableWebMvcSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
@Autowired
private UsuarioDAO usuarioDAO;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/produtos/form").hasRole("ADMIN")
.antMatchers("/carrinho/**").permitAll()
.antMatchers(HttpMethod.POST, "/produtos").hasRole("ADMIN")
.antMatchers(HttpMethod.GET, "/produtos").permitAll()
.antMatchers("/produtos/**").permitAll() // o que vier para frente **
.antMatchers("/").permitAll() // permite acessar a home
.antMatchers("/resources/**").permitAll()
.anyRequest().authenticated() // toda requisição vai verificar se está autenticado
.and().formLogin(); // se nao tiver vai soliciar o login;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(usuarioDAO).passwordEncoder(new BCryptPasswordEncoder());
}
}
package br.com.casadocodigo.loja.conf;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SpringSecurityFilterConfiguration extends AbstractSecurityWebApplicationInitializer {
}
package br.com.casadocodigo.loja.Daos;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;
import br.com.casadocodigo.loja.models.Usuario;
@Repository
public class UsuarioDAO implements UserDetailsService {
@PersistenceContext
private EntityManager manager;
@Override
public Usuario loadUserByUsername(String email) {
List<Usuario> usuarios = manager.createQuery("select u From Usuario u where u.email = :email", Usuario.class)
.setParameter("email", email).getResultList();
if (usuarios.isEmpty()) {
throw new UsernameNotFoundException("Usuario " + email + " não foi encontrado");
}
return usuarios.get(0);
}
}
package br.com.casadocodigo.loja.models;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
@Entity
public class Usuario implements UserDetails{
private static final long serialVersionUID = 8875792777127007029L;
@Id
private String email;
private String senha;
private String nome;
@OneToMany(fetch = FetchType.EAGER)
private List<Role> roles = new ArrayList<Role>();
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public List<Role> getRoles() {
return roles;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.roles;
}
@Override
public String getPassword() {
return this.senha;
}
@Override
public String getUsername() {
return this.email;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
package br.com.casadocodigo.loja.models;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.springframework.security.core.GrantedAuthority;
@Entity
public class Role implements GrantedAuthority{
private static final long serialVersionUID = 7872503757574608017L;
@Id
private String nome;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
@Override
public String getAuthority() {
return this.nome;
}
}