简体   繁体   中英

Adding bcrypt to Spring Boot Security

I've got the below working code to authenticate users calling my Spring Boot API against an Oracle database and match their roles to urls. I'm now looking to use bcrypt to store/retrieve these from the database.

Do I need to create my own custom userDetails for this or is it possible to simply use what I have below. I'm not overly familiar with Spring Boot so any help appreciated.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired  
    private BasicAuthenticationPoint basicAuthenticationPoint;  

    @Autowired
    DataSource dataSource;

    @Override
    public void configure(HttpSecurity httpSecurity) throws Exception{
        httpSecurity.httpBasic().authenticationEntryPoint(basicAuthenticationPoint);

        httpSecurity.authorizeRequests()
            .antMatchers("/v1/test/*").hasRole("USER");

    }

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource)
            .usersByUsernameQuery("SELECT USERNAME,SECRET_KEY, ENABLED FROM USERS WHERE USERNAME=?")
            .authoritiesByUsernameQuery(
                "SELECT A.USERNAME, B.ROLE_NAME"
                + " FROM USERS A, ROLES B, USER_ROLES C"
                + " WHERE C.USER_ID = A.USER_ID AND C.ROLE_ID = B.ROLE_ID AND A.USERNAME=?"
            );
    }
}

Just add a .passwordEncoder(enocder) to your jdbcAuthentication() like so:

    auth.jdbcAuthentication()
        .dataSource(dataSource)
        .usersByUsernameQuery("SELECT USERNAME,SECRET_KEY, ENABLED FROM USERS WHERE USERNAME=?")
        .authoritiesByUsernameQuery(
            "SELECT A.USERNAME, B.ROLE_NAME"
            + " FROM USERS A, ROLES B, USER_ROLES C"
            + " WHERE C.USER_ID = A.USER_ID AND C.ROLE_ID = B.ROLE_ID AND A.USERNAME=?"
        )
        .passwordEncoder(new BCryptPasswordEncoder());

If you want to reuse the password encoder you can create a bean out of it and inject it where needed.

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