简体   繁体   English

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

[英]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.

相关问题 尝试使用 dynamodb 和 graphql 运行我的 Spring Boot 应用程序时,我不断收到此 @bean 错误 - I keep getting this @bean error when trying to run my spring boot app with dynamodb and graphql 运行 Spring 启动应用程序时,我不断收到 Whitelabel 错误页面 - I keep getting a Whitelabel Error Page when running Spring Boot Application 提交Login spring引导项目时报错403 - Error 403 when I submit the Login spring boot project 可以配置 Java 日志记录以使用 Spring Boot 日志记录吗? - can I configure Java logging to make use of Spring Boot logging? 尝试使用 thymeleaf 进行 Spring Boot 表单验证,但出现我无法弄清楚的错误 - Attempting Spring Boot form validation with thymeleaf, but getting an error that I can't figure out 我可以运行一个空的 spring 引导应用程序而不会出现错误吗? - Can I run an empty spring boot application without getting an Error? 如何禁用Spring Boot日志记录配置? - How can I disable Spring Boot logging configuration? 如何替换 spring boot 2.0 中的默认日志系统 - How can I replace the default logging system in spring boot 2.0 在 Spring Boot 中,如何只为某些用户启用日志记录? - In Spring Boot, how can I enable logging only for certain users? Spring 引导 - 无法排除默认日志记录 - Spring Boot - Can't exclude default logging
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM