简体   繁体   中英

Spring MVC not authenticating versus database

We are working with Spring MVC 4.0, but we are unable to autheticate users against database. We have the following Java security configuration class:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;

/**
 * Configura el acceso a la aplicación para los usuarios.
 */
@Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    String queryUsers = "SELECT acod_usuario as username, ades_clave as password, true as enabled " +
                        "FROM t_usuarios " +
                        "WHERE acod_usuario = ?";
    String queryAuth = "SELECT acod_usuario as username, 'ROLE_USER' as role" +
                       "FROM t_usuarios " +
                       "WHERE acod_usuario = ?";
    auth.jdbcAuthentication().dataSource(dataSource).
        usersByUsernameQuery(queryUsers).
        authoritiesByUsernameQuery(queryAuth);
}

/**
 * Configuración de la seguridad HTTP.
 */
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().
            antMatchers("/home","/403","/resources/**").permitAll().
            anyRequest().hasAnyRole("ROLE_USER, ANONYMOUS").
            and().
         formLogin().
            loginPage("/home").usernameParameter("username").passwordParameter("password").
            and().
         logout().
            permitAll().
            and().
         exceptionHandling().accessDeniedPage("/403").and().
            csrf();
}
}

Pagres authorization is working fine, but we are unable to make login works with a valid user. All users can entry the application, instead they do not exist in database. Data source configuration is working fine too,

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.justinfact.web.*")
public class WebConfig extends WebMvcConfigurerAdapter {
private UsuarioDAO usuarioDAO;
private CatalogosDAO catalogosDAO;
private CFEDAO cfeDAO;

/**
 * Registra la base de datos de backend, creando un connection pool.
 * 
 * @return DataSource
 */
@Bean
public DataSource dataSource() {
    BasicDataSource basicDataSource = new BasicDataSource();
    basicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
    basicDataSource.setUrl("jdbc:mysql://localhost:3306/db");
    basicDataSource.setUsername("xxxxx");
    basicDataSource.setPassword("xxxxx");
    basicDataSource.setInitialSize(5);
    basicDataSource.setMaxActive(10);
    basicDataSource.setAccessToUnderlyingConnectionAllowed(true);
    return basicDataSource;
}

/**
 * Se registra el template para trabajar con JDBC
 * 
 * @return JdbcTemplate
 */
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
    return new JdbcTemplate(dataSource);
}

but it seems that no query is executing. We have tested the querys and works fine for us. Login page is an standard one:

<div class="contenedor">
    <img src="<s:url value='resources' />/images/logo.jpg"     width="220" height="90" border="0" />
<h1>
    Acceso Sistema  
</h1>

<br>
<c:url value="login" var="loginURL"/>
<sf:form id="homeForm" action="${loginURL}" method="POST" commandName="user">
    <c:if test="${param.error != null}">
        <p>Usuario o clave incorrecta</p>
    </c:if>
    <c:if test="${param.logout != null}">
        <p>Ha salido correctamente de la aplicación</p>
    </c:if>
    <div class="div_form">
        <sf:input path="rut" placeholder="RUT empresa"/>
    </div>
    <div class="div_form">
        <sf:input path="username" placeholder="nombre de usuario"/><sf:errors path="username"  />
    </div>
    <div class="div_form">
        <sf:password path="password" placeholder="contraseña"/>
    </div>
    <div><a id="ingresar" href="#">Acceder</a></div>
    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
</sf:form>

And we have a basic controller file to manage this operations:

@Controller
public class HomeController {

private static final Logger logger = LoggerFactory.getLogger(HomeController.class);


/**
 * Simply selects the home view to render by returning its name.
 */
@RequestMapping(value = "home", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
    logger.info("Welcome home! The client locale is {}.", locale);

    /*
    Date date = new Date();
    DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
    String formattedDate = dateFormat.format(date);
    model.addAttribute("serverTime", formattedDate );
    */
    model.addAttribute("user",new Login());
    return "home";
}

/**
 * Realiza la gestión de la operación de login/acceso al sistema con usuario y clave.
 * 
 * @param user
 * @param model
 * @return
 */
@RequestMapping(value = "login", method = RequestMethod.POST)
public String login(@Valid Login user, Model model, Errors errors) {
    logger.info("en Login");
    logger.info(errors.toString());
    logger.info(user.toString());
    System.out.println(user);
    model.addAttribute("user", user);
    return "login";
}
}

What we are doing the wrong way?

Thanks in advance

Solved,

One problem was I have a "/login" action with POST in my controllers, that overwrites the default login action from Spring security. Now it's working with some other changes.

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM