首页 > 解决方案 > Spring Boot, implement login with encoded password

问题描述

I am developing a Java password manager using Spring Boot, Spring Sec, mySQL. My login page works great, i have two kind of user: ADMIN and NORMAL. Admin can create a new user, and when it happens, the new user will be persisted on db with the hashed password and a clear text username. My webController class below:

@Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

@RequestMapping(value = { "/login" })
    public String login() {
        return "login";
    }

@RequestMapping(value = "/insertuser", method = RequestMethod.GET)
    public String insertuser(ModelMap modelMap) {
        modelMap.put("user", new User());
        return "insertuser";
    }

    @RequestMapping(value = "insertuser", method = RequestMethod.POST)
    public String insertuser(
            @ModelAttribute("user") User user, ModelMap modelMap) throws NoSuchAlgorithmException, InvalidKeySpecException {

        String encodedPassword = bCryptPasswordEncoder.encode(user.getPassword());
        user.setPassword(encodedPassword);

        userService.addUser(user);
        return "home";
    }

And here we have the SecurityConfig class

@Configuration
@EnableAutoConfiguration
public class SecurityConfig extends WebSecurityConfigurerAdapter  {

    @Autowired
    DataSource dataSource;

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource)
                .usersByUsernameQuery("select username,password,enabled from user where username=?")
                .authoritiesByUsernameQuery("select usernameusr, role from userroles where usernameusr=?");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/", "/home").permitAll().antMatchers("/admin", "/getrole", "/getusers", "/insertuser").hasRole("ADMIN")
                .anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll().and().logout()
                .permitAll();   

        http.exceptionHandling().accessDeniedPage("/403");
        }
}

On db the new user saved by the admin has the hash of is password.

username: anakin
password: $2a$10$.AVpjhbsVKfGtMxiKlTts.2yiiKB0gF7xu2lrL6o3iEWqIMDgM43.
password in clear text is: vader

Now if i logout and try to login with the user credential anakin/vader i get a bad credential error.

How can i implement a correct login using the encoded password? I know that we need to get the submitted clear password, apply the hash function and if it matches with the hash password on db the login conclude successfully, but how can i implement this approach?

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:th="http://www.thymeleaf.org"
    xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>PASSWORDMANAGER</title>

    <div th:replace="fragments/header :: header-css"/>
</head>
<body>
<div th:replace="fragments/header :: header"/>

    <h1 style="text-align: center">
        <font size="20" color="blue">MAIPASSWORD HOME</font>
    </h1>


    <div style="text-align: center" th:if="${param.error}">
        <h1 style="color: red">Bad Credentials. Try again.</h1>
    </div>
    <div style="text-align: center" th:if="${param.logout}">
        <h1 style="color: blue">Logged out.</h1>
    </div>
    <form style="text-align: center" th:action="@{/login}" method="post">
        <p>
            <input type="text" name="username" value="" placeholder="username" />
        </p>
        <p>
            <input type="password" name="password" value=""
                placeholder="password" />
        </p>
        <p class="submit">
            <input type="submit" value="Log In" />
        </p>
    </form>
    <div th:replace="fragments/footer :: footer"/>

</body>
</html>

标签: javaspringhashspring-securitylogin

解决方案


In your configAuthentication call passwordEncoder at the end of your auth object, and pass in your autowired password encoder. This will automatically handle the encoding of the password and attempt the login with it.


推荐阅读