Creating the security config

This is a Java configuration class for Spring Security that enables users to configure Spring Security easily without the use of XML. Create a secure config file named SecurityConfiguration.kt. Here's the code for the class:

@Configuration
@EnableWebSecurity
class SecurityConfiguration: WebSecurityConfigurerAdapter() {

@Throws(Exception::class)
override fun configure(auth: AuthenticationManagerBuilder?) {
auth!!
.inMemoryAuthentication()
.passwordEncoder(passwordEncoder())
// user1 as USER
.withUser("sunnat")
.password(passwordEncoder().encode("password"))
.roles("USER")
.and()

// user2 as ADMIN
.withUser("admin")
.password(passwordEncoder().encode("password"))
.roles("ADMIN")
}

@Throws(Exception::class)
override fun configure(http: HttpSecurity?) {
http!!
.antMatcher("/**").authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic()
}

@Bean(name = [BeanIds.AUTHENTICATION_MANAGER])
@Throws(Exception::class)
override fun authenticationManagerBean(): AuthenticationManager {
return super.authenticationManagerBean()
}


@Bean
fun passwordEncoder(): BCryptPasswordEncoder {
return BCryptPasswordEncoder(16)
}
}

This is a configuration class, so you need to add the @Configuration annotation. 

This class extends WebSecurityConfigurerAdapter, and the @EnableWebSecurity annotation provides the web-based security mechanism.  

According to this code, we use two @Bean annotations in the required functions. We inject AuthenticationManager and configure it via AuthorizationServerEndpointsConfigurer. The BCryptPasswordEncoder instance is used to encode the passwords.

In configure(http: HttpSecurity?), note the following:

In configure(auth: AuthenticationManagerBuilder?), note the following: