I have following problem I have simple register and logging to the site with Spring Security after successful registration ( user added to the db i added screen below)
When i want to log in i just go in url:
http://localhost:8080/login?error
And nothing else like error i don`t know what is wrong the username and password is correct
This is my view login.html
<form method="POST" th:action="@{/login}" id="loginForm">
<div class="form-group">
<label for="username">Nazwa użytkownika: </label>
<input type="text" name="username" id="username" class="form-control">
</div>
<div class="form-group">
<label for="password">Hasło: </label>
<input type="password" name="password" id="password" class="form-control">
</div>
<br>
<div class="form-group">
<input type="submit" value="Zaloguj się" class="btn btn-primary">
</div>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</form>
and SecurityConfig
package my.taco.web;
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.builders.WebSecurity;
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;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Bean
public PasswordEncoder encoder(){
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
auth
.userDetailsService(userDetailsService)
.passwordEncoder(encoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception{
http
.authorizeRequests()
.antMatchers("/design","/orders").access("hasRole('ROLE_USER')")
.antMatchers("/","/**").access("permitAll")
.and()
.formLogin()
.loginPage("/login")
.usernameParameter("username")
.passwordParameter("password")
.defaultSuccessUrl("/design",true)
.and()
.logout()
.logoutSuccessUrl("/");
}
@Override
public void configure(WebSecurity web){
web
.ignoring()
.antMatchers("/h2/**");
}
}
I need to add something like logging controller or what? i`m newbie in Spring Thank you for help everyone.
Added implements UserDetailsService in reply to the comment
package my.taco.services;
import my.taco.data.UserRepository;
import my.taco.models.User;
import org.springframework.beans.factory.annotation.Autowired;
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
public class UserRepositoryUserDetailsService implements UserDetailsService {
private UserRepository userRepo;
@Autowired
public UserRepositoryUserDetailsService(UserRepository userRepo){
this.userRepo=userRepo;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException{
User user=userRepo.findByUsername(username);
if(user!=null){
return user;
}
throw new UsernameNotFoundException("Użytkwonik "+username+ " nie został znaleziony");
}
}
Added User class
package my.taco.models;
import lombok.AccessLevel;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.util.Arrays;
import java.util.Collection;
@Entity
@Data
@NoArgsConstructor(access = AccessLevel.PRIVATE,force = true)
@RequiredArgsConstructor
public class User implements UserDetails {
private static final long serialVersionUID=1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private final String username;
private final String password;
private final String fullname;
private final String street;
private final String city;
private final String state;
private final String zip;
private final String phoneNumber;
@Override
public Collection<? extends GrantedAuthority> getAuthorities(){
return Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"));
}
@Override
public boolean isAccountNonExpired(){
return true;
}
@Override
public boolean isAccountNonLocked(){
return true;
}
@Override
public boolean isCredentialsNonExpired(){
return true;
}
@Override
public boolean isEnabled(){
return true;
}
}
Hello, in this case I would recommend you to implement UserDetailsService:
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
private final LoginService loginService;
@Autowired
public UserDetailsServiceImpl(LoginService loginService) {
this.loginService = loginService;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
LoginDto user = loginService.findUserByUsername(username);
if (user == null) {
throw new UsernameNotFoundException(username + " not found");
}
return new User(user.getUsername(), user.getPassword(), List.of(new SimpleGrantedAuthority(user.getRole())));
}
}
You should debug your code in the loadUserByUsername
method, which will give you a clear understanding of your problem: the required username does not come, there is no user in the database or something else. Keep in mind, the User
class from the package org.springframework.security.core.userdetails
. Have a nice day
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.