Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package cz.muni.pa165.carparkapp.configuration; import cz.muni.pa165.carparkapp.DAO.EmployeeDAO; import cz.muni.pa165.carparkapp.Entities.Employee; import cz.muni.pa165.carparkapp.dto.EmployeeDTO; import cz.muni.pa165.carparkapp.service.EmployeeService; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; import org.apache.commons.codec.digest.DigestUtils; @Component(value = "authenticationProvider") public class MyAuthenticationProvider implements AuthenticationProvider { @Autowired private EmployeeService employeeService; @Autowired private EmployeeDAO dao; @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = authentication.getName(); String password = (String) authentication.getCredentials(); password = DigestUtils.shaHex(password); Employee user = null; for (Employee e : dao.getAllEmployees()) { //System.out.println(e); if (e.getUserName().equals(username)) { user = e; break; } } if (user == null) { throw new BadCredentialsException("Username not found."); } if (!password.equals(user.getPassword())) { throw new BadCredentialsException("Wrong password."); } List<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority("ROLE_" + user.getRole())); return new UsernamePasswordAuthenticationToken(username, password, authorities); } @Override public boolean supports(Class<?> arg0) { return true; } @Bean public PasswordEncoder passwordEncoder() { PasswordEncoder encoder = new BCryptPasswordEncoder(); return encoder; } }