Tomcat error because of BCrypt code incorrectly (Spring Security) [on hold]

42
August 21, 2019, at 06:00 AM

I wrote a project. I want when an admin or user logs on to the site, their passwords are encrypted(BCrypt) in the MySQL database.

So far their passwords are not encrypted (BCrypt)

Tomcat error You can see the code, maybe I wrote it wrong.

Security Config

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/user/**").hasRole("USER")
                .antMatchers("/**").permitAll()
                .and()
                .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/allStudents")
                .and()
                .logout()
                .and()
                .csrf().disable();
    }
   @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

Admin Controller

@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private StudentService studentService;
    @Autowired
    private UserService userService;
    @GetMapping("/allStudentsAdmin")
    public ModelAndView allStudentsForUser() {
        ModelAndView mv = new ModelAndView();
        List<Student> studentList = studentService.getAllStudents();
        mv.addObject("studentList", studentList);
        mv.setViewName("allStudentsAdmin");
        return mv;
    }
    @GetMapping(value = "/deleteStudent/{id}")
    public ModelAndView deleteUserById(@PathVariable Long id) {
        studentService.deleteStudentById(id);
        ModelAndView mv = new ModelAndView("redirect:/admin/allStudentsAdmin");
        return mv;
    }
    @GetMapping(value = "/editStudent/{id}")
    public ModelAndView displayEditUserForm(@PathVariable Long id) {
        ModelAndView mv = new ModelAndView("adminEditStudent");
        Student student = studentService.getStudentById(id);
        mv.addObject("headerMessage", "Редактирование студента");
        mv.addObject("student", student);
        return mv;
    }
    @PostMapping(value = "/editStudent")
    public String saveEditedUser(
    @RequestParam("id") Long id,
    @RequestParam("name") String name,
    @RequestParam("surname") String surname,
    @RequestParam("avatar") MultipartFile file) {
        try {
            studentService.updateStudent(name, surname, file, studentService.getStudentById(id));
        } catch (FileSystemException ex) {
            ex.printStackTrace();
        } catch (IOException e) {
            return "redirect:/errors";
        }
        return "redirect:/admin/allStudentsAdmin";
    }
    @GetMapping(value = "/addStudentAdmin")
    public ModelAndView displayNewUserForm() {
        ModelAndView mv = new ModelAndView("addStudentAdmin");
        mv.addObject("headerMessage", "Add Student Details");
        mv.addObject("student", new Student());
        return mv;
    }
    @PostMapping(value = "/addStudentAdmin")
    public String saveNewStudent(@RequestParam("name") @NonNull String name,
    @RequestParam("surname") @NonNull String surname,
    @RequestParam("avatar") MultipartFile file)
    throws IOException {
        Student student = new Student();
        student.setSurname(surname);
        student.setName(name);
        if (file != null && !file.isEmpty()) {
            student.setAvatar(studentService.saveAvatarImage(file).getName());
        }
        studentService.saveStudent(student);
        return "redirect:/admin/allStudentsAdmin";
    }
    @GetMapping(value = "/addUser")
    public ModelAndView displayAddUserForm() {
        ModelAndView mv = new ModelAndView("addUser");
        mv.addObject("user", new User());
        return mv;
    }
    @PostMapping(value = "/addUser", consumes = "multipart/form-data")
    public String saveNewUser(@ModelAttribute User user) {
        userService.saveUser(user);
        return "redirect:/admin/allUsers";
    }
    @GetMapping("/allUsers")
    public ModelAndView allUsers(@ModelAttribute User user) {
        ModelAndView mv = new ModelAndView("allUsers");
        List<User> users = userService.getAll();
        mv.addObject("users", users);
        return mv;
    }
    @GetMapping("/editUser/{id}")
    public ModelAndView editUser(@PathVariable Long id) {
        Optional<User> user = userService.findUser(id);
        if (user.isPresent()) {
            ModelAndView mv = new ModelAndView("editUser");
            mv.addObject("user", user.get());
            return mv;
        }
        return new ModelAndView("redirect:/admin/allUsers");
    }
    @PostMapping("/editUser")
    public String saveEditedUser(@ModelAttribute User user) {
        userService.updateUser(user);
        return "redirect:/admin/allUsers";
    }

     @GetMapping(value = "/deleteUser/{id}")
    public ModelAndView deleteClientById(@PathVariable Long id) {
        userService.deleteAccountById(id);
        ModelAndView mv = new ModelAndView("redirect:/admin/allUsers");
        return mv;
    }
}

UserService

public interface UserService {
    User saveUser(User user);
    List<User> getAll();
    Optional<User> findUser(Long id);
    User updateUser(User user);
    boolean deleteAccountById(Long id);
}    

UserServiceImpl

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository repository;

    @Autowired
    public UserServiceImpl(UserRepository repository) {
        super();
        this.repository = repository;
    }
    @Override
    public List<User> getAll() {
        return (List<User>) repository.findAll();
    }
    @Override
    public Optional<User> findUser(Long id) {
        return repository.findById(id);
    }
    @Override
    public User saveUser(User user) {
        return repository.save(user);
    }
    @Override
    public boolean deleteAccountById(Long id) {
        try {
            repository.deleteById(id);
            return true;
        } catch (Exception ex) {
            return false;
        }
    }
    @Override
    public User updateUser(User user) {
        User targetUser = repository.findById(user.getId()).get();
        if (user.getLogin() != null) {
            targetUser.setLogin(user.getLogin());
        }
        if (user.getRole() != null) {
            targetUser.setRole(user.getRole());
        }
        if (user.getPassword() != null) {
            targetUser.setPassword(user.getPassword());
        }
        return repository.save(targetUser);

    }
}

User.JAVA

@Entity
@Table(name = "users")
public class User implements Serializable, UserDetails {
    @Id
    @GeneratedValue
    private Long id;
    private String login;
    private String password;
    private String role;
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getLogin() {
        return login;
    }
    public void setLogin(String login) {
        this.login = login;
    }
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return Collections.singleton(new SchoolAuthority(role));
    }
    @Override
    public String getPassword() {
        return password;
    }
    @Override
    public String getUsername() {
        return login;
    }
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }
    @Override
    public boolean isEnabled() {
        return true;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getRole() {
        return role;
    }
    public void setRole(String role) {
        this.role = role;
    }
    class SchoolAuthority implements GrantedAuthority {
        String role;
        public SchoolAuthority(String role) {
            this.role = role;
        }
        @Override
        public String getAuthority() {
            return role;
        }
    }
    @Override
    public String toString() {
        return "User{" +
        "id=" + id +
        ", login='" + login + '\'' +
        ", password='" + password + '\'' +
        ", role='" + role + '\'' +
        '}';
    }
}

Authorization Controller

@Controller
public class AuthorizationController {
    private static final String ROLE_ADMIN = "ROLE_ADMIN";
    private static final String ROLE_USER = "ROLE_USER";
    @Autowired
    StudentService studentService;
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String loginPage(@RequestParam(value = "error", required = false) String error,
            @RequestParam(value = "logout", required = false) String logout,
            Model model) {
        String errorMessage = null;
        if (error != null) {
            errorMessage = "Username or Password is incorrect !!";
        }
        if (logout != null) {
            errorMessage = "You have been successfully logged out !!";
        }
        model.addAttribute("errorMessage", errorMessage);
        return "login";
    }
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logoutPage(HttpServletRequest request, HttpServletResponse response) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null) {
            new SecurityContextLogoutHandler().logout(request, response, auth);
        }
        return "redirect:/";
    }
    @RequestMapping(value = {"/allStudents", "/"},  method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView displayAllStudents() {
        Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication()
                .getAuthorities();
        if(containRole(authorities, ROLE_ADMIN)){
            return new ModelAndView("redirect:/admin/allStudentsAdmin");
        }
        if(containRole(authorities, ROLE_USER)){
            return new ModelAndView("redirect:/user/allStudentsUser");
        }
        ModelAndView mv = new ModelAndView("allStudents");
        mv.addObject("studentList", studentService.getAllStudents());
        return mv;
    }
    @GetMapping("/addStudent")
    public ModelAndView editStudent(){
        Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication()
                .getAuthorities();
        if(containRole(authorities, ROLE_ADMIN)){
            return new ModelAndView("redirect:/admin/addStudentAdmin");
        }
        if(containRole(authorities, ROLE_USER)){
            return new ModelAndView("redirect:/user/addStudentUser");
        }
        ModelAndView mv = new ModelAndView("allStudents");
        mv.addObject("studentList", studentService.getAllStudents());
        return mv;
    }
    private boolean containRole(Collection<? extends GrantedAuthority> authorities, String role){
        for (GrantedAuthority grantedAuthority : authorities) {
            if (grantedAuthority.getAuthority().equals(role)) {
                return true;
            }
        }
        return false;
    }
}

AddUser.JSP

<body>
<div class="add">
    <br>
    <br>
    <br>
    <br>
    <center>
        <form:form method="POST" action="${pageContext.request.contextPath}/admin/addUser"
                   enctype="multipart/form-data">
            <table>
                <tr>
                    <td><label path="Login">Login</label></td>
                    <td><input type="text" name="login"/></td>
                </tr>
                <tr>
                    <td><label path="Password">Password</label></td>
                    <td><input type="text" name="password"/></td>
                </tr>
                <tr>
                    <td><label path="Role">Выберите роль</label></td>
                    <td>
                        <select path="role" name="role" required>
                            <option>ROLE_ADMIN</option>
                            <option selected>ROLE_USER</option>
                        </select>
                    </td>

                    <td><input class="btn btn-primary" type="submit" value="Submit"></td>
                </tr>
            </table>
        </form:form>
    </center>
</div>
</body>
READ ALSO
Handling empty XML nodes when converting to JSON using Jackson

Handling empty XML nodes when converting to JSON using Jackson

I read in an XML file (provided by another system, so i cannot control it) in order to convert it to JSONUsing Jackson, I am seeing some undesirable behavior where any "empty" nodes in the source XML file are being converted to JSON with "\n " as the content

42
Adding an interface with override to a method using Javassist

Adding an interface with override to a method using Javassist

I'm using Javassist to add some code in a method(the create method), but I can't seem to find a way to add an annotation The code I tried looks like this:

32
How to modify parameters for testing using excel or other approach?

How to modify parameters for testing using excel or other approach?

I would like to separate the testing parameters from the testing script to achieve data-driven automation testingI have to be under java 1

12
Understanding exceptions in Java with interfaces

Understanding exceptions in Java with interfaces

I have the following code which has two interfaces which have two methods of the same nameHowever each method throws a different type of Exception

17