简体   繁体   中英

Spring Boot Security 4 custom PasswordEncoder

I have a password field in the database containing MD5(username + password). How would I implement this in Spring Security + JdbcAuthentication. I know that this is not secure by any means, but it is a legacy database, which I must talk to. My current code looks like this:

auth.jdbcAuthentication()
    .dataSource(dataSource)
    .usersByUsernameQuery("select login, password, 1 as enabled from 
                           login where login=?")
    .authoritiesByUsernameQuery("select login,role" +
                    "  from login lo" +
                    "  join login_role lor on lo.login_id = lor.login_id" +
                    "  join role gr on lor.role_id = gr.role_id" +
                    " where login=?")

If I send the hashed value as password the authentication works. I think I would have to configure some password encoder.

You can configure the whole authentication into your applicationContext.xlm like this:

    <sec:authentication-manager>
        <sec:authentication-provider>
            <sec:password-encoder ref="encoder" /> // And here is an encoder that will encode a password which comes from login form.
            <sec:jdbc-user-service data-source-ref="dataSource"
                users-by-username-query="your query"
                authorities-by-username-query="your query for authentication table" />
        </sec:authentication-provider>
    </sec:authentication-manager>

I tried it in school today and it worked for me. I found it easiest way to solve my authority problem and hope that it also will be suitable solution for you.

PS. Sorry, not sure about how correct my answer will be displayed. Was only reader here for about an year and now decided to join and write some questions myself

I've gone with the hacky way and rewrote the Request Parameters in a ServletFilter. The Key for this was to use a custom HttpServletRequestWrapper to be able to modify the request.

Now username+password is passed as password to the md5 encoder. Had some upper/lowercase Problems, but adjusting SQL solved this.

You should do like following

@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) 
    throws Exception {

    auth.jdbcAuthentication().dataSource(dataSource)
        .passwordEncoder(passwordEncoder())
        .usersByUsernameQuery("sql...")
        .authoritiesByUsernameQuery("sql...");
}   

@Bean
public PasswordEncoder passwordEncoder(){
    PasswordEncoder encoder = new BCryptPasswordEncoder();
    return encoder;
}

Hope its help to you.

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