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:

  • antMatcher("/**").authorizeRequests() means that this HttpSecurity will only be applicable to URLs that start with /**.
  • anyRequest().authenticated() utilization guarantees that any request to our application requires the client to be confirmed.
  • formLogin() allows users to authenticate with form-based logins.
  • httpBasic() means the user is validated with HTTP Basic authentication.

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

  • inMemoryAuthentication() includes memory confirmation to AuthenticationManagerBuilder and restores InMemoryUserDetailsManagerConfigurer to permit customization of the in-memory validation.
  • passwordEncoder(passwordEncoder()) means that the password will be an encoded password.
  • withUser("user") and withUser("admin") is the name of the user.
  • password(passwordEncoder().encode("password")) is the encoded password.
  • roles("USER") and roles("ADMIN") is the role of a user.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.95.245