To add the configuration for Spring Security of our project, create a file named SSConfig.kt in the application package using the following code:
@Configuration
@EnableWebSecurity
class SSConfig: WebSecurityConfigurerAdapter() {
@Autowired
private val authEntryPoint: AuthenticationEntryPoint? = null
@Throws(Exception::class)
override fun configure(http: HttpSecurity) {
http.csrf().disable().authorizeRequests()
.anyRequest().authenticated()
.and().httpBasic()
.authenticationEntryPoint(authEntryPoint)
}
@Autowired
@Throws(Exception::class)
fun configureGlobal(auth: AuthenticationManagerBuilder) {
auth.inMemoryAuthentication()
.withUser("sunnat629")
.password(PasswordEncoderFactories.createDelegatingPasswordEncoder()
.encode("password"))
.roles("USER")
}
}
We've annotated this class with @Configuration, which helps in the Spring annotation-based configuration. @EnableWebSecurity will enable the web security support of Spring Security.
We've extended WebSecurityConfigurerAdapter and this will give us access to overriding and customizing the Spring features. We're using HTTP Basic Authentication and all of our requests will be authenticated using this.
If the authentication fails, we need to handle this. To do so, create an authentication entry point class named AuthenticationEntryPoint.kt and autowire it. It will help to retry this process again in case of the failure.
Here we are using the sunnat629 username, the password password, and the USER role.