What programming should be done to use Spring Security with Jboss with annotations?

Asked

Viewed 359 times

4

According to requirements of a project that is in the research phase, I need a large distributed system to work properly with Spring, at the moment I am having a lot of difficulties in integrating Spring Security 3.2 with Jboss EAP 6.3.

It is a little difficult to define exactly where the difficulty is, as I’m doing new tests new obstacles arise, so I need a concrete code reference that works authentication and basic authorization (In Memory) for mapping and methods calls.

What settings, parameterizations and programming should be done to use them using annotations (Servlet 3.1)?

Link to the base codes that are constantly evolving due to tests and studies: http://bit.ly/EstudoSpringSecurityComJBoss

  • There are many ways to set up and use Spring Security, plus different ways to integrate it with different technologies, usually some MVC framework like Spring MVC, but effectively can be integrated with any Servlets-based technology. Without defining exactly the characteristics of your project and what technologies it will adopt in the Vision and Controller layers, it is impossible to talk about settings and parameters without rewriting or simply summarizing existing documentation.

  • For a new project, I strongly suggest going from Sprint Boot, where setting up and implementing a prototype with Spring Security can be as simple as a 15 minute tutorial (depending, of course, on the developer’s experience with Java). In addition to the facilities of Spring Boot that is based on conventions (Coc), breaking you can still get rid of containers and headaches is what is to maintain and configure these little monsters, because Spring Boot works very well with a container standalone.

  • @utluiz, I understand, but the project was planned with Jboss. Thank you.

  • Even I have already found the answer and I will be doing a small tutorial when I have solved all the problems, part of the solution is in this question: http://answall.com/questions/73435/exemplo-do-spring-security-n%C3%A3o-funciona-no-jboss-o-que-deve-ser-para-comp? lq=1#comment151084_73435

  • Delfino, can you explain why you want to ask the question as a wiki? Maybe it makes more sense to just put the answer (to tell you the truth, I didn’t quite understand your goal with this).

  • If I put it as a wiki, it was a mistake,.

  • You signaled asking to turn into wiki :) So I’ll leave as it is, when posting the answer is up to you put it as wiki (contact me if you need help).

  • Well, honestly I don’t remember. Hehehe. But I think valid also as Wiki, many people stop using jboss because they find it complicated and the solution can be very simple as far as I got in the studies.

  • @bfavaretto, I am looking to replicate such action and did not find how it was done, when I create a question I have no option to mark as being Community Wiki, and after the sent question, there is no flag option for me, even if I edit it there is such option. I think it must have really been a mistake. Thank you.

  • @Delfino I just set up Spring Security on a Wildfly server (jboss version 8). If you’re interested I can share the setup and project with you on github.

  • Thanks @adelmo00 I do, thanks again.

Show 6 more comments

1 answer

1


The project uses Spring Security, JPA and JAX-RS. I haven’t put in any MVC framework yet. I have tested the authentication and it is working properly on Wildfly 8.2.

Pom.xml was generated using the jboss Forge tool and went 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 the configuration:

@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;
}}

User 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 Assignment 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;
}}

User 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;
    }
  }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.