Stefano Pisano
Stefano Pisano

Reputation: 438

Spring Security always 302

I'm trying to put Spring Security in my Spring Boot project but when I try to login, the server always returns 302.

package it.expenses.expenses;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
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.builders.WebSecurity;
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 javax.sql.DataSource;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers( "/getHomePage").permitAll()
                .anyRequest().fullyAuthenticated()
                .and()
                .formLogin()
                .loginPage("/getLoginPage")
                .loginProcessingUrl("/login")
                .usernameParameter("username")
                .passwordParameter("password")
                .defaultSuccessUrl("/getHomePage")
                .permitAll()
                .and()
                .authorizeRequests()
                .antMatchers("/", "/resources/static/**").permitAll()
                .anyRequest().authenticated();


    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/script/**");
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
    }
}

Actually the controller need only to returns templates.

This is the login page

  <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <title> Spring Boot MVC Security using Thymeleaf </title>
    <link rel="stylesheet" href="/css/styles.css"/>
</head>
<body>
<h3> Spring Boot MVC Security using Thymeleaf </h3>
<p th:if="${param.error}" class="error">
    Bad Credentials
</p>
<form action="login" method="POST">
    User Name : <input type="text" name="username"/> <br/><br/>
    Password: <input type="password" name="password"/> <br/><br/>
    <input type="submit" value="Login"/>
</form>
</body>
</html>

UserDetailService:

@Service
public class UserDetailsServiceImpl implements UserDetailsService{

    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String userName)
            throws UsernameNotFoundException {
        Users user = userDao.getActiveUser(userName);
        GrantedAuthority authority = new SimpleGrantedAuthority(user.getRole());
        UserDetails userDetails = new User(user.getUsername(),
                user.getPassword(), Arrays.asList(authority));
        return userDetails;
    }
}

This is the project https://github.com/StefanoPisano/expenses

Upvotes: 0

Views: 1761

Answers (1)

Kyle Anderson
Kyle Anderson

Reputation: 7051

Your Security Configuration works, but what I'm not able to see is what records have you saved in the Users table.

Example:

+--------+---------+--------------------------------------------------------------+------+----------+
| idUser | enabled | password                                                     | role | username |
+--------+---------+--------------------------------------------------------------+------+----------+
|      1 |       1 | password                                                     | USER | user     |
|      2 |       1 | $2a$10$eriuZaZsEWKB3wcpPMyexe4Ywe1AX9u148nrLmTTEIq6ORdLNiyp6 | USER | user2    |
+--------+---------+--------------------------------------------------------------+------+----------+

Since you've enabled password encoding:

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
   BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
   auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}

You must store the encoded password in the Users table (not the plain-text password)

The example data above shows user and user2 with the same password (one plain-text, the other encoded). If user tries to login, you'll get a BadCredentialsException since the BCryptPasswordEncoder is expecting an encoded password

Upvotes: 1

Related Questions