User authentication with H2 database in Kotlin Spring Boot Application

Asked

Viewed 265 times

1

Problem: Authenticate user using H2 database in Spring Security

Context: The application is made using Spring, the user class is this

@Entity
data class Usuario(
        @NotEmpty
        var nome:String = "",
        @NotEmpty
        var login:String = "",
        @NotEmpty
        var senha:String = "",
        @OneToMany(cascade= arrayOf(CascadeType.ALL), mappedBy="usuario")
        var simulacoes:MutableSet<Simulacao> = mutableSetOf(),
        @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
        var id:Int  = 0
)

Repository of the class :

interface UsuarioRep:JpaRepository<Usuario,Int>{
    fun findByLogin(login:String):Usuario
}

Configuration of Springsecurity:

@Configuration
class SecurityConfig : WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity): Unit {
        http
                .authorizeRequests()
                .antMatchers("/","/cadastro").permitAll()
                .antMatchers("/principal").hasRole("USER")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                .logout()
                .permitAll()

        http.exceptionHandling().accessDeniedPage("/");
    }

    @Autowired
    fun configAuthentication(auth: AuthenticationManagerBuilder){
        //
    }
}

I spent a few hours researching and without success, the official documentation is in java and the tutorials are also scarce.

From what I understand I must create a UserDetailsService, but how it can be done in Kotlin?

1 answer

1


The problem was solved using authentication by JDBC

Queries are provisional while due modifications are not made in the database

@Autowired
fun configAuthentication(auth: AuthenticationManagerBuilder){
    auth.jdbcAuthentication().dataSource(dataSource)
            .usersByUsernameQuery("select username , password, 'true' as enabled from USUARIO where username=?")
            .authoritiesByUsernameQuery("select username,role from USUARIO where username=?")
            .passwordEncoder(BCryptPasswordEncoder())
}

The first one needs to search for the user name parameter (in the case username), the password( defined as password), and the 'enabled' status (in the case provisionally always true).

The second needs to fetch the username and scroll.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.