Skip to content

Latest commit

 

History

History
258 lines (218 loc) · 6 KB

File metadata and controls

258 lines (218 loc) · 6 KB

Spring Security

Database

Role Repository

@Entity
@Table(name = "role")
@Data
public class Role {
	
	@Id
	@GeneratedValue(strategy = GenerationType.UUID)
	private String id;
	private String role;
    @ManyToMany(mappedBy = "roles")
	private List<User> users;

UserDetailService Class

@Service
public class CustomeUserDetailService implements UserDetailsService{
	
	@Autowired
	private LoginService loginService;
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException{
		
		User userApp = this.loginService.findUserByUsername(username);
		List<GrantedAuthority> auths = new ArrayList();
		
		if(userApp != null) {
			List<Role> roles = userApp.getRoles();
			if(roles.size()>0) {
				for(Role role:roles) {
					auths.add(new SimpleGrantedAuthority(role.getRole()));
					auths.add(new SimpleGrantedAuthority(role.getRole()));
				}
			}
			UserDetails user = org.springframework.security.core.userdetails.User.withUsername(userApp.getUsername())
					.password(userApp.getPassword())
					.authorities(auths)
					.build();
			
			return user;
		}else {
			throw new UsernameNotFoundException("User not Found!");
		}
	}
}

User Repository

@Entity
@Data
@Table(name = "appuser")
public class User {

	@Id
	@GeneratedValue(strategy = GenerationType.UUID)
	private String id;
	
	@NotNull
	@NotBlank
	@NotEmpty
	@Size(min=4 ,max=100)
	@Column(nullable = false, unique = true)
	private String username;
	
	@NotNull
	@NotBlank
	@NotEmpty
	@Size(min=4 ,max=100)
	private String password;
	
	@Email
	@Column(nullable = false, unique = true)
	private String email;
	
	private boolean enabled = true;
	
	@ManyToMany(fetch = FetchType.EAGER)
	@JoinTable(
			name = "user_role",
			joinColumns = @JoinColumn(
					name = "user_id", referencedColumnName = "id"),
			inverseJoinColumns = @JoinColumn(
					name ="role_id", referencedColumnName = "id"))
	private List<Role> roles;

Dependency

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
<dependency>
  <groupId>org.springframework.security</groupId>
  <artifactId>spring-security-test</artifactId>
  <scope>test</scope>
</dependency>

SecurityConfig

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Autowired
	private CustomeUserDetailService customeUserDetailService;

	@Bean
	public DaoAuthenticationProvider authenticationProvider() {
		DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
		authProvider.setUserDetailsService(customeUserDetailService);
		authProvider.setPasswordEncoder(bCryptPasswordEncoder());
		return authProvider;
	}
	
	@Bean
	public BCryptPasswordEncoder bCryptPasswordEncoder() {
		return new BCryptPasswordEncoder();

	}
	
	@Bean
	public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception{
		
		httpSecurity.authorizeHttpRequests((authorize) -> 
					authorize
					.requestMatchers("/login_v1/**").permitAll()
					.anyRequest().authenticated()
					).formLogin(
                            form -> form
                                    .loginPage("/login")
                                    //.loginProcessingUrl("/login")
                                    //.defaultSuccessUrl("/")
                                    .permitAll()
                    )
					.logout(
                            logout -> logout
                                    .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                                    .permitAll()
                    );

            return httpSecurity.build();
	}

}

INIT User DB

@Autowired
private RoleRepo roleRepo;

@Autowired
private UserRepo userRepo;

//@PostConstruct
public void index() {
	//		Create Role
	Role roleOperator = new Role();
	Role roleUser = new Role();
	Role roleAdmin = new Role();
	
	roleOperator.setRole("operator");
	roleUser.setRole("user");
	roleAdmin.setRole("admin");
	
	this.roleRepo.save(roleOperator);
	this.roleRepo.save(roleUser);
	this.roleRepo.save(roleAdmin);
	
	//		Operator
	List<Role> operatorListRole = new ArrayList();
	operatorListRole.add(roleOperator);
	
	//		User
	List<Role> userListRole = new ArrayList<>();
	userListRole.add(roleUser);
	
	//		Admin
	List<Role> adminListRole = new ArrayList<>();
	adminListRole.add(roleAdmin);
	
	//		Create Operator
	User userOperator = new User();
	userOperator.setUsername("operator");
	userOperator.setEmail("[email protected]");
	userOperator.setPassword(new BCryptPasswordEncoder().encode("operator123"));
	userOperator.setRoles(operatorListRole);
	
	//		Create User
	User userCservice = new User();
	userCservice.setUsername("user");
	userCservice.setEmail("[email protected]");
	userCservice.setPassword(new BCryptPasswordEncoder().encode("cservice123"));
	userCservice.setRoles(userListRole);
	
	//		Create Admin
	User userAdmin = new User();
	userAdmin.setUsername("admin");
	userAdmin.setEmail("[email protected]");
	userAdmin.setPassword(new BCryptPasswordEncoder().encode("admin123"));
	userAdmin.setRoles(adminListRole);
	
	this.userRepo.save(userOperator);
	this.userRepo.save(userAdmin);
	this.userRepo.save(userCservice);
}

HTML Code

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org">
	<head>
		<title>Please Log In</title>
	</head>
	<body>
		<h1>Please Log In</h1>
		<div th:if="${param.error}">
			Invalid username and password.</div>
		<div th:if="${param.logout}">
			You have been logged out.</div>
		<form th:action="proxy.php?url=https%3A%2F%2Fgithub.com%2F%40%7B%2Flogin%7D" method="post">
			<div>
			<input type="text" name="username" placeholder="Username"/>
			</div>
			<div>
			<input type="password" name="password" placeholder="Password"/>
			</div>
			<input type="submit" value="Log in" />
		</form>
	</body>
</html>

Handle Login

@Controller
@RequestMapping("/login")
class LoginController {
	@GetMapping
	String login() {
		return "pages/login_v";
	}
}

Reference

https://docs.spring.io/spring-security/reference/servlet/authorization/authorize-http-requests.html