failure of login page in thymeleaf

Viewed 149

I create login page and it fetch username and password from database but when i enter correct username and password it throw invalid credential exception .I check every thing properly and define everything. I want when user successful login he can see products and search products. but my login not working .it crashed every time login.html

<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">

<head th:replace="/fragments/head"></head>

<body>

<nav th:replace="/fragments/nav :: nav-front"></nav>

<div class="container-fluid mt-5">
    <div class="row">
        <div th:replace="/fragments/categories"></div>
        <div class="col"></div>
        <div class="col-6 text-center">

            <h3 class="display-4">Login</h3>

            <div class="alert alert-danger" th:if="${param.error}">
                Invalid credentials
            </div>

            <form method="post" th:action="@{/login}">

                <div class="form-group">
                    <label>Username:</label>
                    <input type="text" class="form-control" name="username" id="username" placeholder="Username">
                </div>

                <div class="form-group">
                    <label>Password:</label>
                    <input type="password" class="form-control" name="password" id="password" placeholder="Password">
                </div>

                <button class="btn btn-danger mb-5">Login</button>

                <p>
                    Click <a th:href="@{/register}">here</a> to register.
                </p>

            </form>

        </div>
        <div class="col"></div>
    </div>
</div>

<div th:replace="/fragments/footer"></div>

</body>

</html>

pagesController.kt

package com.nilmani.cmsshopingcart.controller

import com.nilmani.cmsshopingcart.model.Page
import com.nilmani.cmsshopingcart.repository.PageRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping

@Controller
@RequestMapping("/")
class PagesController {
    @Autowired
    private lateinit var pageRepository: PageRepository

    @GetMapping
    fun home(model: Model?):String{
        val page: Page? = pageRepository.findBySlug("home")
        if (model != null) {
            model.addAttribute("page",page)
        }
        return "page"
    }
    @GetMapping("/login")
    fun login():String{
        return "login"
    }

    @GetMapping("/{slug}")
    fun page(@PathVariable slug: String, model: Model): String? {
        val page: Page = pageRepository.findBySlug(slug) ?: return "redirect:/"
        model.addAttribute("page", page)
        return "page"
    }
}

UserRepositoryUserDetailsService.kt

package com.nilmani.cmsshopingcart.security

import com.nilmani.cmsshopingcart.model.Admin
import com.nilmani.cmsshopingcart.model.UserEntity
import com.nilmani.cmsshopingcart.repository.AdminRepository
import com.nilmani.cmsshopingcart.repository.UserRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.core.userdetails.UsernameNotFoundException
import org.springframework.stereotype.Service

@Service
class UserRepositoryUserDetailsService : UserDetailsService {
    @Autowired
    private lateinit var userRepo:UserRepository
    @Autowired
    private lateinit var adminRepo:AdminRepository
    @Throws(UsernameNotFoundException::class)
    override fun loadUserByUsername(email: String): UserDetails {
        val user: UserEntity? = userRepo.findByUsername(email)
        val admin: Admin? = adminRepo.findByUsername(email)

        if (user != null) {
            return User(user.username,user.password,ArrayList())
        }

        if (admin != null) {
            return admin
        }

        throw UsernameNotFoundException("User: $email not found!")
    }
}

UserEntity.kt

package com.nilmani.cmsshopingcart.model

import lombok.Data
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.core.userdetails.UserDetails
import java.util.*
import javax.persistence.*
import javax.validation.constraints.Email
import javax.validation.constraints.Size
import kotlin.jvm.Transient
@Data
@Entity
@Table(name = "user")
data class UserEntity(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id:Int=0,
    @Size(min = 5,message = "Name must be attlist 5 character long")
    private var username:String="",
    @Size(min = 8,message = "Password contain above 8 character long")
    private var password:String="",
    @Transient
    val confirmPassword:String="",
    @Email(message = "please enter a valid email")
    val email:String="",
    @Size(min = 10,message = "phone number must be 10 digit")
    val phoneNumber:String="",

    ):UserDetails{
    override fun getAuthorities(): List<SimpleGrantedAuthority> {
        return listOf(SimpleGrantedAuthority("ROLE_USER"))
    }

    override fun getPassword(): String {
        return password
    }

    override fun getUsername(): String {
        return username
    }

    override fun isAccountNonExpired(): Boolean {
        return true
    }

    override fun isAccountNonLocked(): Boolean {
        return true
    }

    override fun isCredentialsNonExpired(): Boolean {
        return true
    }

    override fun isEnabled(): Boolean {
       return true
    }

}

UserRepository.kt

package com.nilmani.cmsshopingcart.repository


import com.nilmani.cmsshopingcart.model.UserEntity
import org.springframework.data.jpa.repository.JpaRepository

interface UserRepository : JpaRepository<UserEntity,Int> {
    fun findByUsername(email:String):UserEntity?
}

SecurityConfig.kt

package com.nilmani.cmsshopingcart.security

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Service

@Service
@Configuration
@EnableWebSecurity
class SecurityConfig : WebSecurityConfigurerAdapter() {

    @Autowired
    private lateinit var userDetailsService: UserDetailsService

    @Bean
    fun encoder(): PasswordEncoder {
        return BCryptPasswordEncoder()
    }

    @Throws(java.lang.Exception::class)
    override fun configure(auth: AuthenticationManagerBuilder?) {
        auth
            ?.userDetailsService(userDetailsService)
            ?.passwordEncoder(encoder())
    }

    @Throws(Exception::class)
    override fun configure(http: HttpSecurity) {
        http
            .authorizeRequests()
            .antMatchers("/category/**").hasAnyRole("USER", "ADMIN")
            .antMatchers("/admin/**").hasAnyRole("USER")
            .antMatchers("/").permitAll()
            .and()
            .formLogin()
            .loginPage("/login")
            .and()
            .logout()
            .logoutSuccessUrl("/")
            .and()
            .exceptionHandling()
            .accessDeniedPage("/")
    }
}

what is the region of failure of my loginPage

1 Answers

if you don't want to encrypt password spring automatically encrypted password. so in that case use NoOpPasswordEncoder.getInstance() instead BCryptPasswordEncoder() so change the code

@Bean
    fun encoder(): PasswordEncoder {
        return BCryptPasswordEncoder()
    }

To

 @Bean
    fun encoder(): PasswordEncoder {
        return NoOpPasswordEncoder.getInstance()
    }

and pass the instance of passwordEncoder in AuthenticationManagerBuilder this code works for me fine

Related