Configuración
En este paquete que vamos a crear, aquí vamos a incluir los archivos para configurar apache cassandra para el manejo de datos y spring security para la autentificar y autorizar.Lo primero que vamos a realizar es configurar apache cassandra nos vamos a ecemexico-core y en src/main/java creamos el paquete com.tutosoftware.ecemexico.config
En este paquete creamos la clase CassandraConfig y escribimos lo siguiente:
package com.tutosoftware.ecemexico.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.cassandra.config.CassandraClusterFactoryBean;
import org.springframework.data.cassandra.config.CassandraSessionFactoryBean;
import org.springframework.data.cassandra.config.SchemaAction;
import org.springframework.data.cassandra.core.CassandraOperations;
import org.springframework.data.cassandra.core.CassandraTemplate;
import org.springframework.data.cassandra.core.convert.CassandraConverter;
import org.springframework.data.cassandra.core.convert.MappingCassandraConverter;
import org.springframework.data.cassandra.core.mapping.BasicCassandraMappingContext;
import org.springframework.data.cassandra.core.mapping.CassandraMappingContext;
import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories;
@SuppressWarnings("deprecation")
@Configuration
@PropertySource(value = { "classpath:cassandra.properties" })
@EnableCassandraRepositories(basePackages = { "com.tutosoftware.ecemexico" })
public class CassandraConfig {
@Autowired
private Environment env;
@Bean
public CassandraClusterFactoryBean cluster() {
CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean();
cluster.setContactPoints(env.getProperty("cassandra.contactpoints"));
cluster.setPort(Integer.parseInt(env.getProperty("cassandra.port")));
return cluster;
}
@Bean
public CassandraMappingContext mappingContext() {
return new BasicCassandraMappingContext();
}
@Bean
public CassandraConverter converter() {
return new MappingCassandraConverter(mappingContext());
}
@Bean
public CassandraSessionFactoryBean session() throws Exception {
CassandraSessionFactoryBean session = new CassandraSessionFactoryBean();
session.setCluster(cluster().getObject());
session.setKeyspaceName(env.getProperty("cassandra.keyspace"));
session.setConverter(converter());
session.setSchemaAction(SchemaAction.NONE);
return session;
}
@Bean
public CassandraOperations cassandraTemplate() throws Exception {
return new CassandraTemplate(session().getObject());
}
}
Ahora creamos la clase SecurityConfig
package com.tutosoftware.ecemexico.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
@Autowired
@Qualifier("customUserDetailsService")
UserDetailsService userDetailsService;
@Autowired
CustomSuccessHandler customSuccessHandler;
@Autowired
protected void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
System.out.println("Estoy comprobando password");
auth.userDetailsService(userDetailsService);
auth.authenticationProvider(authenticationProvider());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService);
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.antMatchers("/menu","/registrarPaciente","/guardarPaciente","/mostrarPaciente",
"/buscarExpediente","/exportarExpediente","/buscarExpedienteId",
"/buscarExpedienteCurp","/buscarExpedienteNombre","/mostrarExpediente","/modificarDatosPersonales",
"/actualizarPaciente","/mostrarHistoriaClinica","/mostrarFormHistoria",
"/agregarHistoriaClinica","/mostrarHistoriaClinicaFecha","/mostrarNotasEvolucion",
"/mostrarFormNotas","/agregarNotaEvolucion","/mostrarNotaEvolucionFecha",
"/mostrarRecetas","/mostrarFormReceta","/mostrarRecetaNumero").access("hasRole('USER') or hasRole('ADMIN') ")
.antMatchers("/registrarUsuarioForm","/guardarUsuario","/buscarUsuario",
"/buscarUsuarioForm","/actualizarUsuarioForm","/actualizarUsuario",
"/eliminarUsuario").access("hasRole('ADMIN')")
//.and().formLogin().loginPage("/login")
.and().formLogin().loginPage("/login").successHandler(customSuccessHandler)
.usernameParameter("email").passwordParameter("password")
.and().csrf()
.and().exceptionHandling().accessDeniedPage("/acessoDenegado");
}
}
Nos genera un error porque no esta CustomSuccessHandler.
Ahora creamos la clase CustomSuccessHandler y escrbimos lo siguiente:
package com.tutosoftware.ecemexico.config;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
@Component
public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler{
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
protected void handle(HttpServletRequest request,
HttpServletResponse response, Authentication authentication) throws IOException {
String targetUrl = determineTargetUrl(authentication);
if (response.isCommitted()) {
System.out.println("no puedo redireccionar");
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
protected String determineTargetUrl(Authentication authentication) {
String url="";
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
List<String> roles = new ArrayList<String>();
for (GrantedAuthority a : authorities) {
roles.add(a.getAuthority());
}
if (isDba(roles)) {
url = "/db";
} else if (isAdmin(roles)) {
url = "/menu";
} else if (isUser(roles)) {
url = "/menu";
} else {
url="/accessDenied";
}
return url;
}
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
protected RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
private boolean isUser(List<String> roles) {
if (roles.contains("ROLE_USER")) {
return true;
}
return false;
}
private boolean isAdmin(List<String> roles) {
if (roles.contains("ROLE_ADMIN")) {
return true;
}
return false;
}
private boolean isDba(List<String> roles) {
if (roles.contains("ROLE_DBA")) {
return true;
}
return false;
}
}
Ahora creamos la clase CustomUserDetailsService
package com.tutosoftware.ecemexico.config;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.tutosoftware.ecemexico.entity.Usuario;
import com.tutosoftware.ecemexico.service.UsuarioService;
@Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService{
@Autowired
UsuarioService usuarioService;
@Transactional(readOnly=true)
public UserDetails loadUserByUsername(String email)
throws UsernameNotFoundException {
System.out.println("email : "+email);
Usuario usuario = usuarioService.obtenerUsuario(email);
System.out.println("User : "+usuario);
if(usuario==null){
System.out.println("Usuario no funciona");
throw new UsernameNotFoundException("Usuario no funciona");
}
return new org.springframework.security.core.userdetails.User(usuario.getEmail(),usuario.getPassword(),true,
true,true,true,getGrantedAuthorities(usuario));
}
private List<GrantedAuthority> getGrantedAuthorities(Usuario usuario){
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority("ROLE_"+usuario.getRol()));
return authorities;
}
}
Nos genera un error porque no tine entidad Usuario ni el Servicio UsuarioService que lo crearemos mas adelante esta vez programaremos por paquetes para que se te haga mas facil la creación del proyecto.
Ahora creamos la clase SecurityWebApplicationInitializer para inicializar spring security:
package com.tutosoftware.ecemexico.config;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer{
}
Nos vamos a src/main/resources y aquí creamos el archivo cassandra.properties en el cual agregamos los siguientes datos:
cassandra.contactpoints=localhost,127.0.0.1
cassandra.port=9042
cassandra.keyspace=ecemexicodb
Hasta este momento asi se veria el proyecto.