Mam problem, otóż nie mogę sie zalogować na użytkownika, którego wcześniej dodalem. Dostaje komunikat, o błednym haśle lub loginie, który sam zaimplementowalem w klasie konfiguracyjnej. Dodam, że nie ma problemu z zalogowaniem się bezpośrednie po rejstracji przy pomocy zwracania headers oraz na użytkownika domyślnego, którego autoryzuje w kodzie.
Proszę o pomoc, bo mocno mnie to blokuje i już mase czasu poswięcilem na znalezieniu błędu :(
package doctorsoffice.Patient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/registers")
public class UserController {
UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@PostMapping
public ResponseEntity<UserDto> registerUser(@RequestParam String email, @RequestParam String password, @RequestParam long pesel,
@RequestParam int age, @RequestParam String name, @RequestParam String surname) {
UserDto newUser = userService.registerUser(email, password, pesel, name, surname, age);
// HttpHeaders headers = new HttpHeaders();
// headers.add("Location", "/hello");
// //return new ResponseEntity<UserDto>(newUser, HttpStatus.CREATED);
HttpHeaders headers = new HttpHeaders();
headers.add("Location", "/hello");
return new ResponseEntity<>(headers, HttpStatus.FOUND);
}
}
package doctorsoffice.Security;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class LoginController {
@GetMapping("/hello")
public String helllo() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
return auth.getName();
}
}
package doctorsoffice.Security;
import doctorsoffice.Patient.UserDetailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests()
.antMatchers("/*.html").permitAll()
.anyRequest().permitAll();
//http.httpBasic();
http
.formLogin()
.loginPage("/users/login")
.failureHandler((request, response, exception) -> response.sendError(HttpStatus.BAD_REQUEST.value(),
"Username or password invalid"))
.usernameParameter("email")
.passwordParameter("password")
.defaultSuccessUrl("/hello").permitAll();
http
.logout()
.logoutUrl("/user/logout")
.invalidateHttpSession(true)
.logoutSuccessUrl("/hello")
.permitAll();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("pass").roles("ADMIN");
}
@Override
@Bean
protected UserDetailsService userDetailsService() {
return new UserDetailServiceImpl();
}
// @Override
// public void configure(WebSecurity web) throws Exception {
// web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources",
// "/configuration/security", "/swagger-ui.html", "/webjars/**");
//
// }
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form action="/users/login" method="post">
<div>Email : <input type="text" name="email"/></div>
<div>Password: <input type="password" name="password"/></div>
<div><input type="submit" value="Sign in"/></div>
</form>
</body>
</html>
package doctorsoffice.Patient;
import doctorsoffice.common.LoginAlreadyInUseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.Collections;
@Service
@Transactional
public class UserServiceImpl implements UserService {
private UserRepository userRepository;
private UserMapper userMapper;
private PasswordEncoder passwordEncoder;
@Autowired
public UserServiceImpl(UserRepository userRepository, UserMapper userMapper, PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.userMapper = userMapper;
this.passwordEncoder = passwordEncoder;
}
@Override
public UserDto registerUser(String email, String password, Long pesel, String name, String surname, int age) {
if(userRepository.existsByEmail(email)){
throw new LoginAlreadyInUseException(email);
}
User user = new User();
user.setAge(age);
user.setEmail(email);
user.setName(name);
user.setSurname(surname);
user.setPassword(passwordEncoder.encode(password));
user.setPesel(pesel);
user.setUserRole(UserRoles.ROLE_USER);
userRepository.save(user);
SecurityContext ctx = SecurityContextHolder.getContext();
Authentication auth =
new UsernamePasswordAuthenticationToken(user, null, Collections.emptyList());
ctx.setAuthentication(auth);
return userMapper.toUserDto(user);
}
}