User authentication with H2 bank in Kotlin Spring Boot Application

1

Problem: Authenticate user using H2 database in Spring Security

Context: The application is done 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
)

Class repository:

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

SpringSecurity Configuration:

@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 unsuccessfully, the official documentation is in Java and the tutorials are also scarce.

For what I understand I should create a UserDetailsService , however how can this be done in kotlin?

    
asked by anonymous 14.05.2018 / 00:40

1 answer

1

The problem has been resolved using% co_query authentication

The queries are provisional while the appropriate modifications are not made to 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 username parameter (in the JDBC case), the password (set to username ), and the status 'enabled'.

The second needs to search for the username and scroll to it.

    
15.05.2018 / 00:15