├── README.md ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── javatechie │ │ └── spring │ │ └── security │ │ └── api │ │ ├── SpringSecurityJpaApplication.java │ │ ├── config │ │ └── SecurityConfig.java │ │ ├── controller │ │ ├── AdminController.java │ │ └── ApplicationController.java │ │ ├── model │ │ ├── Role.java │ │ └── User.java │ │ ├── repository │ │ ├── RoleRepository.java │ │ └── UserRepository.java │ │ └── service │ │ ├── CustomUserDetails.java │ │ └── CustomUserDetailsService.java └── resources │ └── application.properties └── test └── java └── com └── javatechie └── spring └── security └── api └── SpringSecurityJpaApplicationTests.java /README.md: -------------------------------------------------------------------------------- 1 | # spring-security-jpa 2 | How to implement spring security connecting with database 3 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | spring-security-jpa 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | spring-security-jpa 12 | spring security example 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.0.1.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-data-jpa 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-security 35 | 36 | 37 | org.springframework.boot 38 | spring-boot-starter-web 39 | 40 | 41 | 42 | org.springframework.boot 43 | spring-boot-devtools 44 | runtime 45 | 46 | 47 | mysql 48 | mysql-connector-java 49 | runtime 50 | 51 | 52 | org.projectlombok 53 | lombok 54 | true 55 | 56 | 57 | org.springframework.boot 58 | spring-boot-starter-test 59 | test 60 | 61 | 62 | org.springframework.security 63 | spring-security-test 64 | test 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | org.springframework.boot 73 | spring-boot-maven-plugin 74 | 75 | 76 | 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /src/main/java/com/javatechie/spring/security/api/SpringSecurityJpaApplication.java: -------------------------------------------------------------------------------- 1 | package com.javatechie.spring.security.api; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringSecurityJpaApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringSecurityJpaApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/javatechie/spring/security/api/config/SecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.javatechie.spring.security.api.config; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 7 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 8 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 9 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 10 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 11 | import org.springframework.security.core.userdetails.UserDetailsService; 12 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 13 | 14 | @Configuration 15 | @EnableWebSecurity 16 | @EnableGlobalMethodSecurity(prePostEnabled = true) 17 | public class SecurityConfig extends WebSecurityConfigurerAdapter { 18 | 19 | @Autowired 20 | private UserDetailsService userDetailsService; 21 | 22 | @Override 23 | protected void configure(AuthenticationManagerBuilder auth) throws Exception { 24 | auth.userDetailsService(userDetailsService).passwordEncoder(encodePWD()); 25 | } 26 | 27 | @Override 28 | protected void configure(HttpSecurity http) throws Exception { 29 | http.csrf().disable(); 30 | 31 | http.authorizeRequests().antMatchers("/rest/**").authenticated().anyRequest().permitAll().and() 32 | .authorizeRequests().antMatchers("/secure/**").authenticated().anyRequest().hasAnyRole("ADMIN").and() 33 | .formLogin().permitAll(); 34 | 35 | } 36 | 37 | @Bean 38 | public BCryptPasswordEncoder encodePWD() { 39 | return new BCryptPasswordEncoder(); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/javatechie/spring/security/api/controller/AdminController.java: -------------------------------------------------------------------------------- 1 | package com.javatechie.spring.security.api.controller; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.security.access.prepost.PreAuthorize; 5 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 6 | import org.springframework.web.bind.annotation.GetMapping; 7 | import org.springframework.web.bind.annotation.PostMapping; 8 | import org.springframework.web.bind.annotation.RequestBody; 9 | import org.springframework.web.bind.annotation.RequestMapping; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | import com.javatechie.spring.security.api.model.User; 13 | import com.javatechie.spring.security.api.repository.UserRepository; 14 | 15 | @RestController 16 | @RequestMapping("/secure/auth/") 17 | public class AdminController { 18 | 19 | @Autowired 20 | private UserRepository userRepository; 21 | 22 | @Autowired 23 | private BCryptPasswordEncoder passwordEncoder; 24 | 25 | /*@PreAuthorize("hasAnyRole('ADMIN')")*/ 26 | @PostMapping("/admin/add") 27 | public String addUserByAdmin(@RequestBody User user) { 28 | String pwd = user.getPassword(); 29 | String encryptPwd = passwordEncoder.encode(pwd); 30 | user.setPassword(encryptPwd); 31 | userRepository.save(user); 32 | return "user added successfully..."; 33 | } 34 | 35 | @PreAuthorize("hasAnyRole('ADMIN')") 36 | @GetMapping("/admin/all") 37 | public String securedHello() { 38 | return "Secured Hello"; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/javatechie/spring/security/api/controller/ApplicationController.java: -------------------------------------------------------------------------------- 1 | package com.javatechie.spring.security.api.controller; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.RequestMapping; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | @RestController 8 | @RequestMapping("/rest/auth") 9 | public class ApplicationController { 10 | 11 | @GetMapping("/process") 12 | public String process() { 13 | return "processing.."; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/javatechie/spring/security/api/model/Role.java: -------------------------------------------------------------------------------- 1 | package com.javatechie.spring.security.api.model; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.GeneratedValue; 5 | import javax.persistence.Id; 6 | 7 | import lombok.Getter; 8 | import lombok.NoArgsConstructor; 9 | import lombok.Setter; 10 | 11 | @Entity 12 | @Getter 13 | @Setter 14 | @NoArgsConstructor 15 | public class Role { 16 | @Id 17 | @GeneratedValue 18 | private int role_id; 19 | private String role; 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/javatechie/spring/security/api/model/User.java: -------------------------------------------------------------------------------- 1 | package com.javatechie.spring.security.api.model; 2 | 3 | import java.util.Set; 4 | 5 | import javax.persistence.CascadeType; 6 | import javax.persistence.Entity; 7 | import javax.persistence.FetchType; 8 | import javax.persistence.Id; 9 | import javax.persistence.JoinColumn; 10 | import javax.persistence.JoinTable; 11 | import javax.persistence.OneToMany; 12 | 13 | import lombok.Getter; 14 | import lombok.Setter; 15 | 16 | @Entity 17 | @Getter 18 | @Setter 19 | public class User { 20 | @Id 21 | private int user_id; 22 | private String username; 23 | private String password; 24 | private String email; 25 | @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) 26 | @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) 27 | private Set roles; 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/javatechie/spring/security/api/repository/RoleRepository.java: -------------------------------------------------------------------------------- 1 | package com.javatechie.spring.security.api.repository; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | 5 | import com.javatechie.spring.security.api.model.Role; 6 | 7 | public interface RoleRepository extends JpaRepository{ 8 | 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/javatechie/spring/security/api/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.javatechie.spring.security.api.repository; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | 5 | import com.javatechie.spring.security.api.model.User; 6 | 7 | public interface UserRepository extends JpaRepository{ 8 | 9 | User findByUsername(String username); 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/javatechie/spring/security/api/service/CustomUserDetails.java: -------------------------------------------------------------------------------- 1 | package com.javatechie.spring.security.api.service; 2 | 3 | import java.util.Collection; 4 | import java.util.stream.Collectors; 5 | 6 | import org.springframework.security.core.GrantedAuthority; 7 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 8 | import org.springframework.security.core.userdetails.UserDetails; 9 | 10 | import com.javatechie.spring.security.api.model.User; 11 | 12 | import lombok.Getter; 13 | import lombok.Setter; 14 | 15 | @Getter 16 | @Setter 17 | public class CustomUserDetails implements UserDetails { 18 | 19 | /** 20 | * 21 | */ 22 | private static final long serialVersionUID = 1256711395932122675L; 23 | private User user; 24 | 25 | @Override 26 | public Collection getAuthorities() { 27 | 28 | return user.getRoles().stream().map(role -> new SimpleGrantedAuthority("ROLE_" + role)) 29 | .collect(Collectors.toList()); 30 | 31 | } 32 | 33 | @Override 34 | public String getPassword() { 35 | return user.getPassword(); 36 | } 37 | 38 | @Override 39 | public String getUsername() { 40 | return user.getUsername(); 41 | } 42 | 43 | @Override 44 | public boolean isAccountNonExpired() { 45 | return true; 46 | } 47 | 48 | @Override 49 | public boolean isAccountNonLocked() { 50 | // TODO Auto-generated method stub 51 | return true; 52 | } 53 | 54 | @Override 55 | public boolean isCredentialsNonExpired() { 56 | // TODO Auto-generated method stub 57 | return true; 58 | } 59 | 60 | @Override 61 | public boolean isEnabled() { 62 | // TODO Auto-generated method stub 63 | return true; 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/com/javatechie/spring/security/api/service/CustomUserDetailsService.java: -------------------------------------------------------------------------------- 1 | package com.javatechie.spring.security.api.service; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.security.core.userdetails.UserDetails; 5 | import org.springframework.security.core.userdetails.UserDetailsService; 6 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 7 | import org.springframework.stereotype.Service; 8 | 9 | import com.javatechie.spring.security.api.model.User; 10 | import com.javatechie.spring.security.api.repository.UserRepository; 11 | 12 | @Service 13 | public class CustomUserDetailsService implements UserDetailsService { 14 | 15 | @Autowired 16 | private UserRepository repository; 17 | 18 | @Override 19 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 20 | User user = repository.findByUsername(username); 21 | CustomUserDetails userDetails = null; 22 | if (user != null) { 23 | userDetails = new CustomUserDetails(); 24 | userDetails.setUser(user); 25 | } else { 26 | throw new UsernameNotFoundException("User not exist with name : " + username); 27 | } 28 | return userDetails; 29 | 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | # =============================== 2 | # = DATA SOURCE 3 | # =============================== 4 | spring.datasource.driver-class-name=com.mysql.jdbc.Driver 5 | spring.datasource.url = jdbc:mysql://localhost:3306/auth 6 | spring.datasource.username = root 7 | spring.datasource.password = cisco 8 | # =============================== 9 | # = JPA / HIBERNATE 10 | # =============================== 11 | spring.jpa.show-sql = true 12 | spring.jpa.hibernate.ddl-auto = update 13 | spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect 14 | hibernate.format_sql=true; 15 | # =============================== -------------------------------------------------------------------------------- /src/test/java/com/javatechie/spring/security/api/SpringSecurityJpaApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.javatechie.spring.security.api; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class SpringSecurityJpaApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | --------------------------------------------------------------------------------