The project uses Spring Security, JPA and JAX-RS. I have not put any MVC framework yet.
I tested the authentication and it works correctly in WildFly 8.2.
Pom.xml was generated using the jBoss forge tool and was including other dependencies.
The SpringSecurityInitializer class extends the abstract class AbstractSecurityWebApplicationInitializer, which internally performs the Servlet Filter record created for any application URL
public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
public SpringSecurityInitializer(){
super(SecurityConfig.class);
}
@Override
protected void beforeSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(servletContext, new MultipartFilter());
}}
SecurityConfig class that is responsible for configuring:
@Configuration
@ComponentScan(basePackages = { "br.com.manager.config", " br.com.manager.service", "br.com.manager.dao" })
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Inject
private AuthenticateUser authenticateUser;
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticateUser);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin().defaultSuccessUrl(UrlUtil.DASHBOARD_INDEX);
http.formLogin().usernameParameter("username").passwordParameter("password");
http.logout().logoutSuccessUrl(UrlUtil.LOGIN_PAGE);
http.logout().invalidateHttpSession(true);
http.authorizeRequests().antMatchers("/dashboard/**").authenticated();
http.authorizeRequests().antMatchers("/**").permitAll();
http.csrf().disable();
}}
AuthenticateUser, used to authenticate the user:
@Named
public class AuthenticateUser implements AuthenticationProvider {
@Inject
private UsuarioService usuarioService;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = (String) authentication.getCredentials();
Usuario usuario = usuarioService.loadUserByUsername(username);
if (usuario == null || !password.equals(usuario.getPassword())) {
throw new BadCredentialsException("Dados não encontrados.");
}
Collection<? extends GrantedAuthority> authorities = usuario.getAuthorities();
return new UsernamePasswordAuthenticationToken(username, password, authorities);
}
@Override
public boolean supports(Class<?> authentication) {
return true;
}}
UserService class should implement the UserDetailsService interface:
@Named
public class UsuarioService implements UserDetailsService {
@Inject
private UsuarioDao usuarioDAO;
@Override
public Usuario loadUserByUsername(String username) throws UsernameNotFoundException {
return usuarioDAO.findByLogin(username);
}}
The User class must implement the UserDetails interface
@Entity(name = "Usuario")
public class Usuario implements Serializable, UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false, unique = true)
private String login;
@Column(nullable = false)
private String nome;
@Column(nullable = false, length = 60)
private String senha;
@ManyToMany(fetch = FetchType.EAGER)
private Set<Atribuicao> atribuicoes;
@Column(unique = true, nullable = false)
private String cpf;
@Column(unique = true, nullable = false)
private String email;
@Column(nullable = true)
private Boolean ativo;
@OneToOne
private Curriculo curriculo;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return atribuicoes;
}
@Override
public String getPassword() {
return senha;
}
@Override
public String getUsername() {
return login;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}}
The Attributions Class must implement the GrantedAuthority interface
@Entity
public class Atribuicao implements Serializable,GrantedAuthority {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(unique = true)
private String nome;
@Override
public String getAuthority() {
return nome;
}}
DatabaseConfig class
@Configuration
@EnableTransactionManagement
public class DatabaseConfig {
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws Exception {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "br.com.manager.model" });
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
public DataSource dataSource() {
JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
dsLookup.setResourceRef(true);
DataSource dataSource = dsLookup.getDataSource("java:jboss/datasources/ManagerDS");
return dataSource;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.show_sql", "true");
properties.setProperty("hibernate.format_sql", "true");
properties.setProperty("hibernate.transaction.flush_before_completion", "true");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
return properties;
}}
UserID class
@Named
public class UsuarioDao {
@PersistenceContext
private EntityManager em;
public Usuario findByLogin(String login) {
try{
Query query = em.createQuery(" select u from Usuario u where u.login like :login").setParameter("login", login);
return (Usuario) query.getSingleResult();
}catch(NoResultException nre ){
return null;
}
}
}