Dmytro Manzhula
Dmytro Manzhula

Reputation: 91

Spring security authentication How to get rid of

Trying to do simple spring boot security test. I can pass the test only with deprecated NoOpPasswordEncoder in globalConfigure() method in SpringSecurityConfig.

it works fine, but is it possible get rid of deprecated NoOpPasswordEncoder?

    @Configuration
    @EnableWebSecurity
    public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {


        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable().authorizeRequests().anyRequest().fullyAuthenticated()
                    .antMatchers("/").permitAll()
                    .and()
                    .formLogin().defaultSuccessUrl("/", true)
                    .loginPage("/login").permitAll().and().logout().permitAll()
                    .and().httpBasic();

        }

        @SuppressWarnings("deprecated")
        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder authBuilder) throws Exception{
            authBuilder.inMemoryAuthentication()
                    .passwordEncoder(NoOpPasswordEncoder.getInstance())
                    .withUser("user").password("user").roles("USER")
                    .and()
                    .withUser("admin").password("admin").roles("USER", "ADMIN");
        }
    }


Testing spring security

@RunWith(SpringJUnit4ClassRunner.class)
@AutoConfigureMockMvc
@SpringBootTest
public class SpringSecurityConfigTest {


    @Autowired
    MockMvc mockMvc;

    @Test
    public void userIsAuthenticatedTest() throws Exception {
        mockMvc.perform(formLogin().user("admin").password("admin"))
                .andExpect(authenticated());
    }
}

Upvotes: 0

Views: 1319

Answers (1)

tine
tine

Reputation: 40

It depends what you want to do exactly. If you just want your test to pass and get rid of the deprecation you can remove the password encoder and add the {noop} prefix to the passwords in your configureGlobal method:

@Autowired
public void configureGlobal(AuthenticationManagerBuilder authBuilder) throws Exception {
    authBuilder.inMemoryAuthentication()
        .withUser("user").password("{noop}user").roles("USER")
        .and()
        .withUser("admin").password("{noop}admin").roles("USER", "ADMIN");
}

Spring Security 5 changed the default password encoder to Delegating Password Encoder which uses the prefix in curly braces to determine which password encoder to use, s. https://docs.spring.io/spring-security/site/docs/5.0.5.RELEASE/reference/htmlsingle/#pe-dpe-format

However, if you want to use this security config in production you should probably use a different encoder anyway.

Upvotes: 1

Related Questions