繁体   English   中英

Spring 开机 登录时一直报错,无法登录

[英]Spring boot I keep getting an error when logging in and I can't login

我想在我的项目中创建一个用户名并登录。 我可以创建用户名,但是我无法使用我创建的用户名登录系统。

我正在尝试使用 spring 安全性登录我的应用程序,但它给了我一个错误。 另外,我将密码以 bcrypted 形式存储在数据库中。 在关联表中,我有用户 ID 和角色 ID。 但我无法登录。 我错过了什么? mysql中的用户表

我无法解决这个问题,你能帮帮我吗?

Default;
username=admin
password=admin

在此处输入图像描述

在此处输入图像描述

这是我的用户存储库

public interface IUserRepository  extends JpaRepository<User, Long> {

Optional<User> findUserByUsername(String username);

这是我的用户服务

Optional<User> findUserByUsername(String username);

void save(User user);


void autoLogin(HttpServletRequest request, String username, String password);

这是我的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);
}

这是我的登录页面

  <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>

这是我的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";
}

这是我的配置

@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();
}

我修正了错误,谢谢。 @Toerktumlar @Roar S。

在表单中添加名称就足够了。

<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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM