[英]Spring boot I keep getting an error when logging in and I can't login
I want to create a username and login in my project.我想在我的项目中创建一个用户名并登录。 I can create username but, I cannot login to the system with the username I created.我可以创建用户名,但是我无法使用我创建的用户名登录系统。
I'm trying to login in my application with spring security, but it gives me an error.我正在尝试使用 spring 安全性登录我的应用程序,但它给了我一个错误。 Also, I'm storing my password in data base in bcrypted form.另外,我将密码以 bcrypted 形式存储在数据库中。 In associate table I have got userid and roleid.在关联表中,我有用户 ID 和角色 ID。 But I can't login.但我无法登录。 What I've missed?我错过了什么? User table in mysql mysql中的用户表
I couldn't solve this problem, can you help me please?我无法解决这个问题,你能帮帮我吗?
Default;
username=admin
password=admin
enter image description here在此处输入图像描述
enter image description here在此处输入图像描述
Here is my User Repository这是我的用户存储库
public interface IUserRepository extends JpaRepository<User, Long> {
Optional<User> findUserByUsername(String username);
Here is my USER SERVİCE这是我的用户服务
Optional<User> findUserByUsername(String username);
void save(User user);
void autoLogin(HttpServletRequest request, String username, String password);
Here is my UserserviceImpl这是我的UserserviceImpl
public class UserServiceImpl implements IUserService {
@Autowired
private IUserRepository iuserRepository;
@Autowired
private IRoleRepository iRoleRepository;
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Autowired
private AuthenticationManager authenticationManager;
@Override
public Optional<User> findUserByUsername(String username) {
return iuserRepository.findUserByUsername(username);
}
@Override
public void save(User user) {
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
user.setActive(true);
Role userRole = iRoleRepository.findRoleByName("ROLE_USER");
user.setRoles(new HashSet<>(Arrays.asList(userRole)));
iuserRepository.save(user);
}
@Override
public void autoLogin(HttpServletRequest request, String username, String password) {
UsernamePasswordAuthenticationToken authToken = new
UsernamePasswordAuthenticationToken(username, password);
authToken.setDetails(new WebAuthenticationDetails(request));
Authentication authentication = authenticationManager.authenticate(authToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
Here is my Login Page这是我的登录页面
<form th:action="@{/login}" method="post">
<div class="form-group">
<label >Username</label>
<input type="text" class="form-control" id="username" required placeholder="Enter Username">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" id="password" required placeholder="Password">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
Here is my Controller public class UserRegistrationController {这是我的Controller public class UserRegistrationController {
@Autowired
private IUserService iUserService;
@Autowired
private IAnimalOwnersService iAnimalOwnersService;
@Autowired
private IAnimalsService iAnimalsService;
@ModelAttribute("user")
public User user() {
return new User();
}
@GetMapping("/")
public String indexPage() {
return "index";
}
@GetMapping("/index")
public String indexPage2() {
return "index";
}
@GetMapping("/register")
public String registerShowPage() {
return "register";
}
@PostMapping("/register")
public String registerPage(@Valid @ModelAttribute("user") User user, BindingResult bindingResult, Model theModel, HttpServletRequest httpServletRequest, RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
return "register";
}
String username = user.getUsername();
String password = user.getPassword();
Optional<User> optionalUser = (iUserService.findUserByUsername(username));
if (optionalUser.isPresent()) {
theModel.addAttribute("alreadyExistsUser", "Username is used");
return "register";
}
iUserService.save(user);
iUserService.autoLogin(httpServletRequest, username, password);
List<String> userRoleNames =
user.getRoles().stream().map(Role::getName).collect(Collectors.toList());
redirectAttributes.addFlashAttribute("username", username);
return "redirect:/index";
}
@GetMapping("/dashboard")
public String dashboardPage(Model theModel) {
Long totalOwners = iAnimalOwnersService.totalUsers();
Long totanAnimals = iAnimalsService.totalAnimals();
theModel.addAttribute("totalOwners", totalOwners);
theModel.addAttribute("totanAnimals", totanAnimals);
return "dashboard";
}
@GetMapping({"/login", "/login.html"})
public String loginPage() {
return "login";
}
Here is my Configuration这是我的配置
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Autowired
private DataSource dataSource;
private final String USERS_QUERY = "select username, password, active from user where username=?";
private final String ROLES_QUERY = "select u.username, r.name from user u inner join user_role ur on(u.user_id=ur.user_id) inner join role r on(ur.role_id=r.role_id) where u.username=?";
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication()
.usersByUsernameQuery(USERS_QUERY)
.authoritiesByUsernameQuery(ROLES_QUERY)
.dataSource(dataSource)
.passwordEncoder(bCryptPasswordEncoder);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers()
.permitAll()
.antMatchers("/register", "/login", "/index", "/")
.permitAll();
http.authorizeRequests().antMatchers("/actuator/**").hasRole("ADMIN");
http.authorizeRequests().anyRequest().authenticated();
http
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/login")
.failureUrl("/login?loginFailed=true")
.usernameParameter("username")
.passwordParameter("password")
.defaultSuccessUrl("/dashboard.html", true)
.and().logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/index");
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
I fixed the error, thank you.我修正了错误,谢谢。 @Toerktumlar @Roar S. @Toerktumlar @Roar S。
Adding a name to the form was enough.在表单中添加名称就足够了。
<div class="form-group">
<label >Username</label>
<input type="text" name="username" class="form-control" id="username" required placeholder="Enter Username">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" id="password" required placeholder="Password">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.