Implementing security

We are implementing basic authentication security. It will be similar to what we covered in Chapter 5, Securing Applications with Spring Security. But there we used inMemoryAuthentication(), and here we will fetch the username and password from the database and implement them for the project using UserDetailsService:

  1. Create a service class named CustomUserDetailsService.kt.
  2. Implement the UserDetailsService and annotated by @Service to make it a service class. Here is the code for this service class:
@Service
class CustomUserDetailsService: UserDetailsService {

@Autowired
private lateinit var userByNameRepository: UserByNameRepository

@Throws(UsernameNotFoundException::class)
override fun loadUserByUsername(username: String): User {
val profile = userByNameRepository.getUserByName(username)

return org.springframework.security.core.userdetails.User(username, profile.password,
AuthorityUtils.createAuthorityList("USER"))
}
}
  1. Here, we autowire the UserByNameRepository.kt repository and override loadUserByUsername(username: String). We will fetch the username and password from the repository and match them with the username and password given by the client. Here is the code for UserByNameRepository.kt:
@Repository
class UserByNameRepository: UserByNameInterface {
@Autowired
private lateinit var jdbcTemplate: JdbcTemplate

override fun getUserByName(username: String): Profile {
val sql = "SELECT * FROM PROFILE WHERE username = ?"
val profile = jdbcTemplate.queryForObject(sql, UserRowMapper(), username)

return profile!!
}

override fun getUserByNamePassword(username: String, password: String): Boolean {
val sql = "SELECT * FROM PROFILE WHERE username = ?, password = ?"
val profile = jdbcTemplate.queryForObject(sql, UserRowMapper(), username, password)
return profile != null
}
}

interface UserByNameInterface {
fun getUserByName(username: String): Profile
fun getUserByNamePassword(username: String, password: String): Boolean
}
  1.  Now create the code for the RowMapper class of the user named UserRowMapper.kt to fetch the user details. Here is a piece of code from this class:
class UserRowMapper : RowMapper<Profile> {

@Throws(SQLException::class)
override fun mapRow(row: ResultSet, rowNumber: Int): Profile? {
val profile = Profile(row.getLong("id"),
row.getString("username"),
row.getString("password"))
return profile
}
}
  1. Let's create a WebSecurityConfigurerAdapter class named SecurityConfigurer.kt and annotate it with @Configuration and @EnableWebSecurity to make a configuration file and enable web security. Here is the code for the SecurityConfigurer.kt class:
@Configuration
@EnableWebSecurity
class SecurityConfigurer : WebSecurityConfigurerAdapter() {

@Autowired
private lateinit var authEntryPoint: AuthenticationEntryPoint

@Autowired
private lateinit var customUserDetailsService: CustomUserDetailsService

@Throws(Exception::class)
override fun configure(http: HttpSecurity) {
http.csrf().disable().authorizeRequests()
.antMatchers("/profile/new").permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.and()
.httpBasic()
.authenticationEntryPoint(authEntryPoint)
}

@Autowired
@Throws(Exception::class)
fun configureGlobal(auth: AuthenticationManagerBuilder) {
auth
.userDetailsService(customUserDetailsService)
.passwordEncoder(getPasswordEncoder())
}

@Bean
fun getPasswordEncoder(): PasswordEncoder {
return object : PasswordEncoder {
override fun encode(charSequence: CharSequence): String {
return charSequence.toString()
}

override fun matches(charSequence: CharSequence, s: String): Boolean {
return true
}
}
}
}

In the previous code, we've done the following:

  • To use this registration URL path, "/profile/new", any user can access. It doesn't need a username and password.
  • We use PasswordEncoder to encode the password.
  • We autowired configureGlobal(auth: AuthenticationManagerBuilder) and passed CustomUserDetailsService via auth.userDetailsService(customUserDetailsService) to check and match the username.
..................Content has been hidden....................

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