├── README.md
├── Spring_Security_1
├── .gitignore
├── .mvn
│ └── wrapper
│ │ ├── maven-wrapper.jar
│ │ └── maven-wrapper.properties
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── com
│ │ │ └── masai
│ │ │ ├── SpringSecurity1Application.java
│ │ │ └── controller
│ │ │ └── MyController.java
│ └── resources
│ │ └── application.properties
│ └── test
│ └── java
│ └── com
│ └── masai
│ └── SpringSecurity1ApplicationTests.java
├── Spring_Security_AuthProvider_Without_JWT
└── SpringSecurityAuthProviderWithoutJwt
│ ├── .gitignore
│ ├── .mvn
│ └── wrapper
│ │ ├── maven-wrapper.jar
│ │ └── maven-wrapper.properties
│ ├── mvnw
│ ├── mvnw.cmd
│ ├── pom.xml
│ └── src
│ ├── main
│ ├── java
│ │ └── com
│ │ │ └── masai
│ │ │ ├── SpringSecurityAuthProviderWithoutJwtApplication.java
│ │ │ ├── config
│ │ │ └── AppConfig.java
│ │ │ ├── controller
│ │ │ ├── CustomerController.java
│ │ │ └── LoginController.java
│ │ │ ├── exception
│ │ │ ├── CustomerException.java
│ │ │ ├── GlobalExceptionHandler.java
│ │ │ └── MyErrorDetails.java
│ │ │ ├── model
│ │ │ └── Customer.java
│ │ │ ├── repository
│ │ │ └── CustomerRepository.java
│ │ │ └── service
│ │ │ ├── CustomerService.java
│ │ │ ├── CustomerServiceImpl.java
│ │ │ └── MyAuthenticationProvider.java
│ └── resources
│ │ └── application.properties
│ └── test
│ └── java
│ └── com
│ └── masai
│ └── SpringSecurityAuthProviderWithoutJwtApplicationTests.java
├── Spring_Security_JWT_With_Role
└── SpringSecurityJwtWithRole
│ ├── .gitignore
│ ├── .mvn
│ └── wrapper
│ │ ├── maven-wrapper.jar
│ │ └── maven-wrapper.properties
│ ├── mvnw
│ ├── mvnw.cmd
│ ├── pom.xml
│ └── src
│ ├── main
│ ├── java
│ │ └── com
│ │ │ └── masai
│ │ │ ├── SpringSecurityJwtWithRoleApplication.java
│ │ │ ├── config
│ │ │ ├── AppConfig.java
│ │ │ ├── JwtTokenGeneratorFilter.java
│ │ │ ├── JwtTokenValidatorFilter.java
│ │ │ └── SecurityConstants.java
│ │ │ ├── controller
│ │ │ ├── CustomerController.java
│ │ │ └── LoginController.java
│ │ │ ├── exception
│ │ │ ├── CustomerException.java
│ │ │ ├── GlobalExceptionHandler.java
│ │ │ └── MyErrorDetails.java
│ │ │ ├── model
│ │ │ ├── Authority.java
│ │ │ └── Customer.java
│ │ │ ├── repository
│ │ │ └── CustomerRepository.java
│ │ │ └── service
│ │ │ ├── CustomerService.java
│ │ │ ├── CustomerServiceImpl.java
│ │ │ ├── CustomerUserDetails.java
│ │ │ └── CustomerUserDetailsService.java
│ └── resources
│ │ └── application.properties
│ └── test
│ └── java
│ └── com
│ └── masai
│ └── SpringSecurityJwtWithRoleApplicationTests.java
├── Spring_Security_With_CustomAthenticationProvider
├── .gitignore
├── .mvn
│ └── wrapper
│ │ ├── maven-wrapper.jar
│ │ └── maven-wrapper.properties
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── com
│ │ │ └── masai
│ │ │ ├── SpringSecurityWithoutJwtApplication.java
│ │ │ ├── config
│ │ │ └── AppConfig.java
│ │ │ ├── controller
│ │ │ ├── CustomerController.java
│ │ │ └── CustomerLoginController.java
│ │ │ ├── exception
│ │ │ ├── CustomError.java
│ │ │ ├── CustomerException.java
│ │ │ └── GlobalExceptionHandler.java
│ │ │ ├── model
│ │ │ └── Customer.java
│ │ │ ├── repository
│ │ │ └── CustomerRepository.java
│ │ │ └── service
│ │ │ ├── CustomAuthenticationProvider.java
│ │ │ ├── CustomerService.java
│ │ │ └── CustomerServiceImpl.java
│ └── resources
│ │ └── application.properties
│ └── test
│ └── java
│ └── com
│ └── masai
│ └── SpringSecurityWithoutJwtApplicationTests.java
├── Spring_Security_With_JWT
├── .gitignore
├── .mvn
│ └── wrapper
│ │ ├── maven-wrapper.jar
│ │ └── maven-wrapper.properties
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── com
│ │ │ └── masai
│ │ │ ├── SpringSecurityWithoutJwtApplication.java
│ │ │ ├── config
│ │ │ ├── AppConfig.java
│ │ │ ├── JwtTokenGeneratorFilter.java
│ │ │ ├── JwtTokenValidatorFilter.java
│ │ │ └── SecurityConstants.java
│ │ │ ├── controller
│ │ │ ├── CustomerController.java
│ │ │ └── CustomerLoginController.java
│ │ │ ├── exception
│ │ │ ├── CustomError.java
│ │ │ ├── CustomerException.java
│ │ │ └── GlobalExceptionHandler.java
│ │ │ ├── model
│ │ │ └── Customer.java
│ │ │ ├── repository
│ │ │ └── CustomerRepository.java
│ │ │ └── service
│ │ │ ├── CustomerService.java
│ │ │ ├── CustomerServiceImpl.java
│ │ │ └── CustomerUserDetailsService.java
│ └── resources
│ │ └── application.properties
│ └── test
│ └── java
│ └── com
│ └── masai
│ └── SpringSecurityWithoutJwtApplicationTests.java
├── Spring_Security_With_JWT2
└── SpringSecurityWithJwt
│ ├── .gitignore
│ ├── .mvn
│ └── wrapper
│ │ ├── maven-wrapper.jar
│ │ └── maven-wrapper.properties
│ ├── mvnw
│ ├── mvnw.cmd
│ ├── pom.xml
│ └── src
│ ├── main
│ ├── java
│ │ └── com
│ │ │ └── masai
│ │ │ ├── SpringSecurityWithJwtApplication.java
│ │ │ ├── config
│ │ │ ├── AppConfig.java
│ │ │ ├── JwtTokenGeneratorFilter.java
│ │ │ ├── JwtTokenValidatorFilter.java
│ │ │ └── SecurityConstants.java
│ │ │ ├── controller
│ │ │ ├── CustomerController.java
│ │ │ └── LoginController.java
│ │ │ ├── exception
│ │ │ ├── CustomerException.java
│ │ │ ├── GlobalExceptionHandler.java
│ │ │ └── MyErrorDetails.java
│ │ │ ├── model
│ │ │ └── Customer.java
│ │ │ ├── repository
│ │ │ └── CustomerRepository.java
│ │ │ └── service
│ │ │ ├── CustomerService.java
│ │ │ ├── CustomerServiceImpl.java
│ │ │ └── CustomerUserDetailsService.java
│ └── resources
│ │ └── application.properties
│ └── test
│ └── java
│ └── com
│ └── masai
│ └── SpringSecurityWithJwtApplicationTests.java
├── Spring_Security_With_JWT2_And_Role
├── .gitignore
├── .mvn
│ └── wrapper
│ │ ├── maven-wrapper.jar
│ │ └── maven-wrapper.properties
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── com
│ │ │ └── masai
│ │ │ ├── SpringSecurityWithoutJwtApplication.java
│ │ │ ├── config
│ │ │ ├── AppConfig.java
│ │ │ ├── JwtTokenGeneratorFilter.java
│ │ │ ├── JwtTokenValidatorFilter.java
│ │ │ └── SecurityConstants.java
│ │ │ ├── controller
│ │ │ ├── CustomerController.java
│ │ │ └── CustomerLoginController.java
│ │ │ ├── exception
│ │ │ ├── CustomError.java
│ │ │ ├── CustomerException.java
│ │ │ └── GlobalExceptionHandler.java
│ │ │ ├── model
│ │ │ └── Customer.java
│ │ │ ├── repository
│ │ │ └── CustomerRepository.java
│ │ │ └── service
│ │ │ ├── CustomerService.java
│ │ │ ├── CustomerServiceImpl.java
│ │ │ └── CustomerUserDetailsService.java
│ └── resources
│ │ └── application.properties
│ └── test
│ └── java
│ └── com
│ └── masai
│ └── SpringSecurityWithoutJwtApplicationTests.java
├── Spring_Security_With_JWT_Cors
└── SpringSecurityWithJwtCors
│ ├── .gitignore
│ ├── .mvn
│ └── wrapper
│ │ ├── maven-wrapper.jar
│ │ └── maven-wrapper.properties
│ ├── mvnw
│ ├── mvnw.cmd
│ ├── pom.xml
│ └── src
│ ├── main
│ ├── java
│ │ └── com
│ │ │ └── masai
│ │ │ ├── SpringSecurityWithJwtCorsApplication.java
│ │ │ ├── config
│ │ │ ├── AppConfig.java
│ │ │ ├── JwtTokenGeneratorFilter.java
│ │ │ ├── JwtTokenValidatorFilter.java
│ │ │ └── SecurityConstants.java
│ │ │ ├── controller
│ │ │ ├── CustomerController.java
│ │ │ └── LoginController.java
│ │ │ ├── exception
│ │ │ ├── CustomerException.java
│ │ │ ├── GlobalExceptionHandler.java
│ │ │ └── MyErrorDetails.java
│ │ │ ├── model
│ │ │ └── Customer.java
│ │ │ ├── repository
│ │ │ └── CustomerRepository.java
│ │ │ └── service
│ │ │ ├── CustomerService.java
│ │ │ ├── CustomerServiceImpl.java
│ │ │ └── CustomerUserDetailsService.java
│ └── resources
│ │ └── application.properties
│ └── test
│ └── java
│ └── com
│ └── masai
│ └── SpringSecurityWithJwtCorsApplicationTests.java
├── Spring_Security_With_Simple_Role_JWT2
└── SpringSecurityWithSimpleRoleJwt2
│ ├── .gitignore
│ ├── .mvn
│ └── wrapper
│ │ ├── maven-wrapper.jar
│ │ └── maven-wrapper.properties
│ ├── mvnw
│ ├── mvnw.cmd
│ ├── pom.xml
│ └── src
│ ├── main
│ ├── java
│ │ └── com
│ │ │ └── masai
│ │ │ ├── SpringSecurityWithSimpleRoleJwt2Application.java
│ │ │ ├── Test.java
│ │ │ ├── config
│ │ │ ├── AppConfig.java
│ │ │ ├── JwtTokenGeneratorFilter.java
│ │ │ ├── JwtTokenValidatorFilter.java
│ │ │ └── SecurityConstants.java
│ │ │ ├── controller
│ │ │ ├── CustomerController.java
│ │ │ └── LoginController.java
│ │ │ ├── exception
│ │ │ ├── CustomerException.java
│ │ │ ├── GlobalExceptionHandler.java
│ │ │ └── MyErrorDetails.java
│ │ │ ├── model
│ │ │ └── Customer.java
│ │ │ ├── repository
│ │ │ └── CustomerRepository.java
│ │ │ └── service
│ │ │ ├── CustomerService.java
│ │ │ ├── CustomerServiceImpl.java
│ │ │ └── CustomerUserDetailsService.java
│ └── resources
│ │ └── application.properties
│ └── test
│ └── java
│ └── com
│ └── masai
│ └── SpringSecurityWithSimpleRoleJwt2ApplicationTests.java
├── Spring_Security_Without_JWT
├── .gitignore
├── .mvn
│ └── wrapper
│ │ ├── maven-wrapper.jar
│ │ └── maven-wrapper.properties
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── com
│ │ │ └── masai
│ │ │ ├── SpringSecurityWithoutJwtApplication.java
│ │ │ ├── config
│ │ │ └── AppConfig.java
│ │ │ ├── controller
│ │ │ ├── CustomerController.java
│ │ │ └── CustomerLoginController.java
│ │ │ ├── exception
│ │ │ ├── CustomError.java
│ │ │ ├── CustomerException.java
│ │ │ └── GlobalExceptionHandler.java
│ │ │ ├── model
│ │ │ └── Customer.java
│ │ │ ├── repository
│ │ │ └── CustomerRepository.java
│ │ │ └── service
│ │ │ ├── CustomerService.java
│ │ │ ├── CustomerServiceImpl.java
│ │ │ └── CustomerUserDetailsService.java
│ └── resources
│ │ └── application.properties
│ └── test
│ └── java
│ └── com
│ └── masai
│ └── SpringSecurityWithoutJwtApplicationTests.java
├── Spring_Security_Without_JWT2
└── SpringSecurityWithoutJwt
│ ├── .gitignore
│ ├── .mvn
│ └── wrapper
│ │ ├── maven-wrapper.jar
│ │ └── maven-wrapper.properties
│ ├── mvnw
│ ├── mvnw.cmd
│ ├── pom.xml
│ └── src
│ ├── main
│ ├── java
│ │ └── com
│ │ │ └── masai
│ │ │ ├── SpringSecurityWithoutJwtApplication.java
│ │ │ ├── config
│ │ │ └── AppConfig.java
│ │ │ ├── controller
│ │ │ ├── CustomerController.java
│ │ │ └── LoginController.java
│ │ │ ├── exception
│ │ │ ├── CustomerException.java
│ │ │ ├── GlobalExceptionHandler.java
│ │ │ └── MyErrorDetails.java
│ │ │ ├── model
│ │ │ └── Customer.java
│ │ │ ├── repository
│ │ │ └── CustomerRepository.java
│ │ │ └── service
│ │ │ ├── CustomerService.java
│ │ │ ├── CustomerServiceImpl.java
│ │ │ └── CustomerUserDetailsService.java
│ └── resources
│ │ └── application.properties
│ └── test
│ └── java
│ └── com
│ └── masai
│ └── SpringSecurityWithoutJwtApplicationTests.java
└── spring_security_live_session
├── SpringBoot_filters.jpg
├── SpringSecurity_session notes.txt
└── spring_security_architecture.jpg
/Spring_Security_1/.gitignore:
--------------------------------------------------------------------------------
1 | HELP.md
2 | target/
3 | !.mvn/wrapper/maven-wrapper.jar
4 | !**/src/main/**/target/
5 | !**/src/test/**/target/
6 |
7 | ### STS ###
8 | .apt_generated
9 | .classpath
10 | .factorypath
11 | .project
12 | .settings
13 | .springBeans
14 | .sts4-cache
15 |
16 | ### IntelliJ IDEA ###
17 | .idea
18 | *.iws
19 | *.iml
20 | *.ipr
21 |
22 | ### NetBeans ###
23 | /nbproject/private/
24 | /nbbuild/
25 | /dist/
26 | /nbdist/
27 | /.nb-gradle/
28 | build/
29 | !**/src/main/**/build/
30 | !**/src/test/**/build/
31 |
32 | ### VS Code ###
33 | .vscode/
34 |
--------------------------------------------------------------------------------
/Spring_Security_1/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Shubh2-0/Spring_Security/a0d45807af1cd2b3f178a105f9b61b8bfaa7c8b6/Spring_Security_1/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/Spring_Security_1/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.3/apache-maven-3.9.3-bin.zip
2 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar
3 |
--------------------------------------------------------------------------------
/Spring_Security_1/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | org.springframework.boot
7 | spring-boot-starter-parent
8 | 3.1.1
9 |
10 |
11 | com.masai
12 | Spring_Security_1
13 | 0.0.1-SNAPSHOT
14 | Spring_Security_1
15 | Demo project for Spring Boot Security
16 |
17 | 17
18 |
19 |
20 |
21 | org.springframework.boot
22 | spring-boot-starter-security
23 |
24 |
25 | org.springframework.boot
26 | spring-boot-starter-web
27 |
28 |
29 |
30 | org.springframework.boot
31 | spring-boot-devtools
32 | runtime
33 | true
34 |
35 |
36 | org.springframework.boot
37 | spring-boot-starter-test
38 | test
39 |
40 |
41 | org.springframework.security
42 | spring-security-test
43 | test
44 |
45 |
46 |
47 |
48 |
49 |
50 | org.springframework.boot
51 | spring-boot-maven-plugin
52 |
53 |
54 |
55 |
56 |
57 |
--------------------------------------------------------------------------------
/Spring_Security_1/src/main/java/com/masai/SpringSecurity1Application.java:
--------------------------------------------------------------------------------
1 | package com.masai;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class SpringSecurity1Application {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(SpringSecurity1Application.class, args);
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/Spring_Security_1/src/main/java/com/masai/controller/MyController.java:
--------------------------------------------------------------------------------
1 | package com.masai.controller;
2 |
3 | import org.springframework.web.bind.annotation.GetMapping;
4 | import org.springframework.web.bind.annotation.RestController;
5 |
6 | @RestController
7 | public class MyController {
8 |
9 | @GetMapping("/hello")
10 | public String sayHello() {
11 |
12 | return "Welcome to Spring Security";
13 | }
14 |
15 | @GetMapping("/learn")
16 | public String sayHello2() {
17 |
18 | return "I am learning Spring Security";
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/Spring_Security_1/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | spring.security.user.name=shubham
2 | spring.security.user.password=12345
3 |
--------------------------------------------------------------------------------
/Spring_Security_1/src/test/java/com/masai/SpringSecurity1ApplicationTests.java:
--------------------------------------------------------------------------------
1 | package com.masai;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.springframework.boot.test.context.SpringBootTest;
5 |
6 | @SpringBootTest
7 | class SpringSecurity1ApplicationTests {
8 |
9 | @Test
10 | void contextLoads() {
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/Spring_Security_AuthProvider_Without_JWT/SpringSecurityAuthProviderWithoutJwt/.gitignore:
--------------------------------------------------------------------------------
1 | HELP.md
2 | target/
3 | !.mvn/wrapper/maven-wrapper.jar
4 | !**/src/main/**/target/
5 | !**/src/test/**/target/
6 |
7 | ### STS ###
8 | .apt_generated
9 | .classpath
10 | .factorypath
11 | .project
12 | .settings
13 | .springBeans
14 | .sts4-cache
15 |
16 | ### IntelliJ IDEA ###
17 | .idea
18 | *.iws
19 | *.iml
20 | *.ipr
21 |
22 | ### NetBeans ###
23 | /nbproject/private/
24 | /nbbuild/
25 | /dist/
26 | /nbdist/
27 | /.nb-gradle/
28 | build/
29 | !**/src/main/**/build/
30 | !**/src/test/**/build/
31 |
32 | ### VS Code ###
33 | .vscode/
34 |
--------------------------------------------------------------------------------
/Spring_Security_AuthProvider_Without_JWT/SpringSecurityAuthProviderWithoutJwt/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Shubh2-0/Spring_Security/a0d45807af1cd2b3f178a105f9b61b8bfaa7c8b6/Spring_Security_AuthProvider_Without_JWT/SpringSecurityAuthProviderWithoutJwt/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/Spring_Security_AuthProvider_Without_JWT/SpringSecurityAuthProviderWithoutJwt/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip
2 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar
3 |
--------------------------------------------------------------------------------
/Spring_Security_AuthProvider_Without_JWT/SpringSecurityAuthProviderWithoutJwt/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | org.springframework.boot
7 | spring-boot-starter-parent
8 | 3.0.1
9 |
10 |
11 | com.masai
12 | SpringSecurityAuthProviderWithoutJwt
13 | 0.0.1-SNAPSHOT
14 | SpringSecurityAuthProviderWithoutJwt
15 | Demo project for Spring Boot
16 |
17 | 17
18 |
19 |
20 |
21 | org.springframework.boot
22 | spring-boot-starter-data-jpa
23 |
24 |
25 | org.springframework.boot
26 | spring-boot-starter-security
27 |
28 |
29 | org.springframework.boot
30 | spring-boot-starter-web
31 |
32 |
33 |
34 | org.springframework.boot
35 | spring-boot-devtools
36 | runtime
37 | true
38 |
39 |
40 | com.mysql
41 | mysql-connector-j
42 | runtime
43 |
44 |
45 | org.projectlombok
46 | lombok
47 | true
48 |
49 |
50 | org.springframework.boot
51 | spring-boot-starter-test
52 | test
53 |
54 |
55 | org.springframework.security
56 | spring-security-test
57 | test
58 |
59 |
60 |
61 |
62 |
63 |
64 | org.springframework.boot
65 | spring-boot-maven-plugin
66 |
67 |
68 |
69 | org.projectlombok
70 | lombok
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
--------------------------------------------------------------------------------
/Spring_Security_AuthProvider_Without_JWT/SpringSecurityAuthProviderWithoutJwt/src/main/java/com/masai/SpringSecurityAuthProviderWithoutJwtApplication.java:
--------------------------------------------------------------------------------
1 | package com.masai;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class SpringSecurityAuthProviderWithoutJwtApplication {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(SpringSecurityAuthProviderWithoutJwtApplication.class, args);
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/Spring_Security_AuthProvider_Without_JWT/SpringSecurityAuthProviderWithoutJwt/src/main/java/com/masai/config/AppConfig.java:
--------------------------------------------------------------------------------
1 | package com.masai.config;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.Configuration;
5 | import org.springframework.http.HttpMethod;
6 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
7 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
8 | import org.springframework.security.crypto.password.PasswordEncoder;
9 | import org.springframework.security.web.SecurityFilterChain;
10 |
11 | @Configuration
12 | public class AppConfig {
13 |
14 | @Bean
15 | public SecurityFilterChain springSecurityConfiguration(HttpSecurity http) throws Exception {
16 |
17 | http.authorizeHttpRequests().requestMatchers(HttpMethod.POST, "/customers").permitAll().anyRequest()
18 | .authenticated().and().csrf().disable().formLogin().and().httpBasic();
19 |
20 | return http.build();
21 |
22 | }
23 |
24 | @Bean
25 | public PasswordEncoder passwordEncoder() {
26 |
27 | return new BCryptPasswordEncoder();
28 |
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/Spring_Security_AuthProvider_Without_JWT/SpringSecurityAuthProviderWithoutJwt/src/main/java/com/masai/controller/CustomerController.java:
--------------------------------------------------------------------------------
1 | package com.masai.controller;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.http.HttpStatus;
7 | import org.springframework.http.ResponseEntity;
8 | import org.springframework.security.crypto.password.PasswordEncoder;
9 | import org.springframework.web.bind.annotation.DeleteMapping;
10 | import org.springframework.web.bind.annotation.GetMapping;
11 | import org.springframework.web.bind.annotation.PathVariable;
12 | import org.springframework.web.bind.annotation.PostMapping;
13 | import org.springframework.web.bind.annotation.PutMapping;
14 | import org.springframework.web.bind.annotation.RequestBody;
15 | import org.springframework.web.bind.annotation.RestController;
16 |
17 | import com.masai.model.Customer;
18 | import com.masai.service.CustomerService;
19 |
20 | import jakarta.websocket.server.PathParam;
21 |
22 | @RestController
23 | public class CustomerController {
24 |
25 |
26 |
27 |
28 | @Autowired
29 | private CustomerService customerService;
30 |
31 | @Autowired
32 | private PasswordEncoder passwordEncoder;
33 |
34 |
35 | @GetMapping("/hello")
36 | public String testHandler() {
37 | return "Welcome to Spring Security";
38 | }
39 |
40 | @PostMapping("/customers")
41 | public ResponseEntity saveCustomerHandler(@RequestBody Customer customer){
42 |
43 | customer.setPassword(passwordEncoder.encode(customer.getPassword()));
44 |
45 | Customer registeredCustomer= customerService.registerCustomer(customer);
46 |
47 | return new ResponseEntity<>(registeredCustomer,HttpStatus.ACCEPTED);
48 |
49 | }
50 |
51 | @GetMapping("/customers/{email}")
52 | public ResponseEntity getCustomerByEmailHandler(@PathVariable("email") String email){
53 |
54 |
55 | Customer customer= customerService.getCustomerDetailsByEmail(email);
56 |
57 | return new ResponseEntity<>(customer,HttpStatus.ACCEPTED);
58 |
59 | }
60 |
61 | @GetMapping("/customers")
62 | public ResponseEntity> getAllCustomerHandler(){
63 |
64 |
65 | List customers= customerService.getAllCustomerDetails();
66 |
67 | return new ResponseEntity<>(customers,HttpStatus.ACCEPTED);
68 |
69 | }
70 |
71 |
72 |
73 | }
74 |
--------------------------------------------------------------------------------
/Spring_Security_AuthProvider_Without_JWT/SpringSecurityAuthProviderWithoutJwt/src/main/java/com/masai/controller/LoginController.java:
--------------------------------------------------------------------------------
1 | package com.masai.controller;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.http.HttpStatus;
5 | import org.springframework.http.ResponseEntity;
6 | import org.springframework.security.authentication.BadCredentialsException;
7 | import org.springframework.security.core.Authentication;
8 | import org.springframework.web.bind.annotation.GetMapping;
9 | import org.springframework.web.bind.annotation.RestController;
10 |
11 | import com.masai.model.Customer;
12 | import com.masai.repository.CustomerRepository;
13 |
14 | @RestController
15 | public class LoginController {
16 |
17 | @Autowired
18 | private CustomerRepository customerRepository;
19 |
20 | @GetMapping("/signIn")
21 | public ResponseEntity getLoggedInCustomerDetailsHandler(Authentication auth){
22 |
23 |
24 | Customer customer= customerRepository.findByEmail(auth.getName()).orElseThrow(() -> new BadCredentialsException("Invalid Username or password"));
25 |
26 | return new ResponseEntity<>(customer, HttpStatus.ACCEPTED);
27 |
28 |
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/Spring_Security_AuthProvider_Without_JWT/SpringSecurityAuthProviderWithoutJwt/src/main/java/com/masai/exception/CustomerException.java:
--------------------------------------------------------------------------------
1 | package com.masai.exception;
2 |
3 | public class CustomerException extends RuntimeException {
4 |
5 | public CustomerException() {
6 | // TODO Auto-generated constructor stub
7 | }
8 |
9 | public CustomerException(String message) {
10 | super(message);
11 | }
12 |
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/Spring_Security_AuthProvider_Without_JWT/SpringSecurityAuthProviderWithoutJwt/src/main/java/com/masai/exception/GlobalExceptionHandler.java:
--------------------------------------------------------------------------------
1 | package com.masai.exception;
2 |
3 | import java.time.LocalDateTime;
4 |
5 | import org.springframework.http.HttpStatus;
6 | import org.springframework.http.ResponseEntity;
7 | import org.springframework.web.bind.annotation.ControllerAdvice;
8 | import org.springframework.web.bind.annotation.ExceptionHandler;
9 | import org.springframework.web.context.request.WebRequest;
10 |
11 | @ControllerAdvice
12 | public class GlobalExceptionHandler {
13 |
14 |
15 |
16 |
17 |
18 | @ExceptionHandler(CustomerException.class)
19 | public ResponseEntity customerExceptionHandler(CustomerException ce, WebRequest req){
20 |
21 |
22 | MyErrorDetails err= new MyErrorDetails();
23 | err.setTimestamp(LocalDateTime.now());
24 | err.setMessage(ce.getMessage());
25 | err.setDetails(req.getDescription(false));
26 |
27 | return new ResponseEntity(err, HttpStatus.BAD_REQUEST);
28 |
29 | }
30 |
31 |
32 |
33 | @ExceptionHandler(Exception.class)
34 | public ResponseEntity otherExceptionHandler(Exception se, WebRequest req){
35 |
36 |
37 | MyErrorDetails err= new MyErrorDetails();
38 | err.setTimestamp(LocalDateTime.now());
39 | err.setMessage(se.getMessage());
40 | err.setDetails(req.getDescription(false));
41 |
42 | return new ResponseEntity(err, HttpStatus.INTERNAL_SERVER_ERROR);
43 |
44 | }
45 |
46 |
47 |
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/Spring_Security_AuthProvider_Without_JWT/SpringSecurityAuthProviderWithoutJwt/src/main/java/com/masai/exception/MyErrorDetails.java:
--------------------------------------------------------------------------------
1 | package com.masai.exception;
2 |
3 | import java.time.LocalDateTime;
4 |
5 | public class MyErrorDetails {
6 |
7 | private LocalDateTime timestamp;
8 | private String message;
9 | private String details;
10 |
11 |
12 | public MyErrorDetails() {
13 | // TODO Auto-generated constructor stub
14 | }
15 |
16 |
17 | public MyErrorDetails(LocalDateTime timestamp, String message, String details) {
18 | super();
19 | this.timestamp = timestamp;
20 | this.message = message;
21 | this.details = details;
22 | }
23 |
24 |
25 | public LocalDateTime getTimestamp() {
26 | return timestamp;
27 | }
28 |
29 |
30 | public void setTimestamp(LocalDateTime timestamp) {
31 | this.timestamp = timestamp;
32 | }
33 |
34 |
35 | public String getMessage() {
36 | return message;
37 | }
38 |
39 |
40 | public void setMessage(String message) {
41 | this.message = message;
42 | }
43 |
44 |
45 | public String getDetails() {
46 | return details;
47 | }
48 |
49 |
50 | public void setDetails(String details) {
51 | this.details = details;
52 | }
53 |
54 |
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/Spring_Security_AuthProvider_Without_JWT/SpringSecurityAuthProviderWithoutJwt/src/main/java/com/masai/model/Customer.java:
--------------------------------------------------------------------------------
1 | package com.masai.model;
2 |
3 | import com.fasterxml.jackson.annotation.JsonProperty;
4 |
5 | import jakarta.persistence.Column;
6 | import jakarta.persistence.Entity;
7 | import jakarta.persistence.GeneratedValue;
8 | import jakarta.persistence.GenerationType;
9 | import jakarta.persistence.Id;
10 | import jakarta.persistence.UniqueConstraint;
11 | import lombok.Data;
12 |
13 | @Entity
14 | @Data
15 | public class Customer {
16 |
17 | @Id
18 | @GeneratedValue(strategy = GenerationType.AUTO)
19 | private Integer custId;
20 | private String name;
21 |
22 | @Column(unique = true)
23 | private String email;
24 | @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
25 | private String password;
26 | private String address;
27 |
28 |
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/Spring_Security_AuthProvider_Without_JWT/SpringSecurityAuthProviderWithoutJwt/src/main/java/com/masai/repository/CustomerRepository.java:
--------------------------------------------------------------------------------
1 | package com.masai.repository;
2 |
3 | import java.util.Optional;
4 |
5 | import org.springframework.data.jpa.repository.JpaRepository;
6 |
7 | import com.masai.model.Customer;
8 |
9 | public interface CustomerRepository extends JpaRepository{
10 |
11 |
12 | public Optional findByEmail(String email);
13 | }
14 |
--------------------------------------------------------------------------------
/Spring_Security_AuthProvider_Without_JWT/SpringSecurityAuthProviderWithoutJwt/src/main/java/com/masai/service/CustomerService.java:
--------------------------------------------------------------------------------
1 | package com.masai.service;
2 | import java.util.List;
3 |
4 | import com.masai.exception.CustomerException;
5 | import com.masai.model.Customer;
6 |
7 | public interface CustomerService {
8 |
9 | public Customer registerCustomer(Customer customer);
10 |
11 | public Customer getCustomerDetailsByEmail(String email)throws CustomerException;
12 |
13 | public List getAllCustomerDetails()throws CustomerException;
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/Spring_Security_AuthProvider_Without_JWT/SpringSecurityAuthProviderWithoutJwt/src/main/java/com/masai/service/CustomerServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.masai.service;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.stereotype.Service;
7 |
8 | import com.masai.exception.CustomerException;
9 | import com.masai.model.Customer;
10 | import com.masai.repository.CustomerRepository;
11 |
12 | @Service
13 | public class CustomerServiceImpl implements CustomerService{
14 |
15 | @Autowired
16 | private CustomerRepository customerRepository;
17 |
18 | @Override
19 | public Customer registerCustomer(Customer customer) throws CustomerException {
20 |
21 | return customerRepository.save(customer);
22 |
23 |
24 | }
25 |
26 | @Override
27 | public Customer getCustomerDetailsByEmail(String email)throws CustomerException {
28 |
29 | return customerRepository.findByEmail(email).orElseThrow(() -> new CustomerException("Customer Not found with Email: "+email));
30 | }
31 |
32 | @Override
33 | public List getAllCustomerDetails()throws CustomerException {
34 |
35 | List customers= customerRepository.findAll();
36 |
37 | if(customers.isEmpty())
38 | throw new CustomerException("No Customer find");
39 |
40 | return customers;
41 |
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/Spring_Security_AuthProvider_Without_JWT/SpringSecurityAuthProviderWithoutJwt/src/main/java/com/masai/service/MyAuthenticationProvider.java:
--------------------------------------------------------------------------------
1 | package com.masai.service;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Optional;
6 |
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.security.authentication.AuthenticationProvider;
9 | import org.springframework.security.authentication.BadCredentialsException;
10 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
11 | import org.springframework.security.core.Authentication;
12 | import org.springframework.security.core.AuthenticationException;
13 | import org.springframework.security.core.GrantedAuthority;
14 | import org.springframework.security.crypto.password.PasswordEncoder;
15 | import org.springframework.stereotype.Component;
16 |
17 | import com.masai.model.Customer;
18 | import com.masai.repository.CustomerRepository;
19 |
20 | @Component
21 | public class MyAuthenticationProvider implements AuthenticationProvider {
22 |
23 |
24 | @Autowired
25 | private CustomerRepository cRepo;
26 |
27 | @Autowired
28 | private PasswordEncoder pEncoder;
29 |
30 | @Override
31 | public Authentication authenticate(Authentication authentication) throws AuthenticationException {
32 |
33 | String username = authentication.getName();
34 | String pwd = authentication.getCredentials().toString();
35 |
36 | System.out.println(username);
37 | System.out.println(pwd);
38 |
39 | Optional opt = cRepo.findByEmail(username);
40 |
41 | if (!opt.isPresent())
42 | throw new BadCredentialsException("No User registerd with this details");
43 | else {
44 |
45 | Customer customer= opt.get();
46 |
47 | if (pEncoder.matches(pwd, customer.getPassword())) {
48 |
49 | List authorities = new ArrayList<>();
50 | //authorities.add(new SimpleGrantedAuthority(customer.getRole()));
51 |
52 | return new UsernamePasswordAuthenticationToken(username, pwd, authorities);
53 |
54 | } else
55 | throw new BadCredentialsException("Invalid Password");
56 |
57 | }
58 |
59 | }
60 |
61 | // to implement this method we can take the support of DAOAP implementaiotn class
62 | @Override
63 | public boolean supports(Class> authentication) {
64 |
65 | return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
66 |
67 | }
68 |
69 | }
70 |
71 |
--------------------------------------------------------------------------------
/Spring_Security_AuthProvider_Without_JWT/SpringSecurityAuthProviderWithoutJwt/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 |
2 | #db specific properties
3 | spring.datasource.url=jdbc:mysql://localhost:3306/masaidb
4 | spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
5 | spring.datasource.username=root
6 | spring.datasource.password=root
7 |
8 | #ORM s/w specific properties
9 | spring.jpa.hibernate.ddl-auto=update
10 | spring.jpa.show-sql=true
11 |
12 | #spring.security.user.name=ratan
13 | #spring.security.user.password=123
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/Spring_Security_AuthProvider_Without_JWT/SpringSecurityAuthProviderWithoutJwt/src/test/java/com/masai/SpringSecurityAuthProviderWithoutJwtApplicationTests.java:
--------------------------------------------------------------------------------
1 | package com.masai;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.springframework.boot.test.context.SpringBootTest;
5 |
6 | @SpringBootTest
7 | class SpringSecurityAuthProviderWithoutJwtApplicationTests {
8 |
9 | @Test
10 | void contextLoads() {
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/Spring_Security_JWT_With_Role/SpringSecurityJwtWithRole/.gitignore:
--------------------------------------------------------------------------------
1 | HELP.md
2 | target/
3 | !.mvn/wrapper/maven-wrapper.jar
4 | !**/src/main/**/target/
5 | !**/src/test/**/target/
6 |
7 | ### STS ###
8 | .apt_generated
9 | .classpath
10 | .factorypath
11 | .project
12 | .settings
13 | .springBeans
14 | .sts4-cache
15 |
16 | ### IntelliJ IDEA ###
17 | .idea
18 | *.iws
19 | *.iml
20 | *.ipr
21 |
22 | ### NetBeans ###
23 | /nbproject/private/
24 | /nbbuild/
25 | /dist/
26 | /nbdist/
27 | /.nb-gradle/
28 | build/
29 | !**/src/main/**/build/
30 | !**/src/test/**/build/
31 |
32 | ### VS Code ###
33 | .vscode/
34 |
--------------------------------------------------------------------------------
/Spring_Security_JWT_With_Role/SpringSecurityJwtWithRole/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Shubh2-0/Spring_Security/a0d45807af1cd2b3f178a105f9b61b8bfaa7c8b6/Spring_Security_JWT_With_Role/SpringSecurityJwtWithRole/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/Spring_Security_JWT_With_Role/SpringSecurityJwtWithRole/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip
2 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar
3 |
--------------------------------------------------------------------------------
/Spring_Security_JWT_With_Role/SpringSecurityJwtWithRole/src/main/java/com/masai/SpringSecurityJwtWithRoleApplication.java:
--------------------------------------------------------------------------------
1 | package com.masai;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class SpringSecurityJwtWithRoleApplication {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(SpringSecurityJwtWithRoleApplication.class, args);
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/Spring_Security_JWT_With_Role/SpringSecurityJwtWithRole/src/main/java/com/masai/config/AppConfig.java:
--------------------------------------------------------------------------------
1 | package com.masai.config;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.Configuration;
5 | import org.springframework.http.HttpMethod;
6 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
7 | import org.springframework.security.config.http.SessionCreationPolicy;
8 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
9 | import org.springframework.security.crypto.password.PasswordEncoder;
10 | import org.springframework.security.web.SecurityFilterChain;
11 | import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
12 |
13 | @Configuration
14 | public class AppConfig {
15 |
16 | @Bean
17 | public SecurityFilterChain springSecurityConfiguration(HttpSecurity http) throws Exception {
18 |
19 | http
20 | .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
21 | .and()
22 | .csrf().disable()
23 | .authorizeHttpRequests()
24 | .requestMatchers(HttpMethod.POST, "/customers")
25 | .permitAll()
26 | .requestMatchers(HttpMethod.GET,"/customers").hasRole("ADMIN")
27 | .requestMatchers(HttpMethod.GET,"/customers/**").hasAnyRole("ADMIN","USER")
28 | .anyRequest()
29 | .authenticated()
30 | .and()
31 | .addFilterAfter(new JwtTokenGeneratorFilter(), BasicAuthenticationFilter.class)
32 | .addFilterBefore(new JwtTokenValidatorFilter(), BasicAuthenticationFilter.class)
33 | .formLogin()
34 | .and()
35 | .httpBasic();
36 |
37 | return http.build();
38 |
39 | }
40 |
41 | @Bean
42 | public PasswordEncoder passwordEncoder() {
43 |
44 | return new BCryptPasswordEncoder();
45 |
46 | }
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/Spring_Security_JWT_With_Role/SpringSecurityJwtWithRole/src/main/java/com/masai/config/JwtTokenValidatorFilter.java:
--------------------------------------------------------------------------------
1 | package com.masai.config;
2 |
3 | import java.io.IOException;
4 | import java.util.List;
5 |
6 | import javax.crypto.SecretKey;
7 |
8 | import org.springframework.security.authentication.BadCredentialsException;
9 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
10 | import org.springframework.security.core.Authentication;
11 | import org.springframework.security.core.GrantedAuthority;
12 | import org.springframework.security.core.authority.AuthorityUtils;
13 | import org.springframework.security.core.context.SecurityContextHolder;
14 | import org.springframework.web.filter.OncePerRequestFilter;
15 |
16 | import io.jsonwebtoken.Claims;
17 | import io.jsonwebtoken.JwtParser;
18 | import io.jsonwebtoken.Jwts;
19 | import io.jsonwebtoken.security.Keys;
20 | import jakarta.servlet.FilterChain;
21 | import jakarta.servlet.ServletException;
22 | import jakarta.servlet.http.HttpServletRequest;
23 | import jakarta.servlet.http.HttpServletResponse;
24 |
25 | public class JwtTokenValidatorFilter extends OncePerRequestFilter {
26 |
27 | @Override
28 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
29 | throws ServletException, IOException {
30 |
31 |
32 | String jwt= request.getHeader(SecurityConstants.JWT_HEADER);
33 |
34 |
35 | if(jwt != null) {
36 |
37 | try {
38 |
39 | //extracting the word Bearer
40 | jwt = jwt.substring(7);
41 |
42 |
43 | SecretKey key= Keys.hmacShaKeyFor(SecurityConstants.JWT_KEY.getBytes());
44 |
45 |
46 |
47 | Claims claims= Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(jwt).getBody();
48 |
49 |
50 | String username= String.valueOf(claims.get("username"));
51 |
52 |
53 | String authorities= (String)claims.get("authorities");
54 |
55 |
56 |
57 | Authentication auth = new UsernamePasswordAuthenticationToken(username, null, AuthorityUtils.commaSeparatedStringToAuthorityList(authorities));
58 |
59 |
60 | // List authorities=(List)claims.get("authorities");
61 | // Authentication auth = new UsernamePasswordAuthenticationToken(username, null, authorities);
62 |
63 |
64 | SecurityContextHolder.getContext().setAuthentication(auth);
65 |
66 | } catch (Exception e) {
67 | throw new BadCredentialsException("Invalid Token received..");
68 | }
69 |
70 |
71 |
72 | }
73 |
74 | filterChain.doFilter(request, response);
75 |
76 |
77 | }
78 |
79 |
80 |
81 | //this time this validation filter has to be executed for all the apis except the /login api
82 |
83 | @Override
84 | protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
85 |
86 | return request.getServletPath().equals("/signIn");
87 | }
88 |
89 | }
90 |
--------------------------------------------------------------------------------
/Spring_Security_JWT_With_Role/SpringSecurityJwtWithRole/src/main/java/com/masai/config/SecurityConstants.java:
--------------------------------------------------------------------------------
1 | package com.masai.config;
2 |
3 | public interface SecurityConstants {
4 |
5 | public static final String JWT_KEY ="secretsfhsfjhdkjngdfjkgfgjdlkfjsdkfjsd";
6 | public static final String JWT_HEADER = "Authorization";
7 |
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/Spring_Security_JWT_With_Role/SpringSecurityJwtWithRole/src/main/java/com/masai/controller/CustomerController.java:
--------------------------------------------------------------------------------
1 | package com.masai.controller;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.http.HttpStatus;
7 | import org.springframework.http.ResponseEntity;
8 | import org.springframework.security.crypto.password.PasswordEncoder;
9 | import org.springframework.web.bind.annotation.DeleteMapping;
10 | import org.springframework.web.bind.annotation.GetMapping;
11 | import org.springframework.web.bind.annotation.PathVariable;
12 | import org.springframework.web.bind.annotation.PostMapping;
13 | import org.springframework.web.bind.annotation.PutMapping;
14 | import org.springframework.web.bind.annotation.RequestBody;
15 | import org.springframework.web.bind.annotation.RestController;
16 |
17 | import com.masai.model.Customer;
18 | import com.masai.service.CustomerService;
19 |
20 | import jakarta.websocket.server.PathParam;
21 |
22 | @RestController
23 | public class CustomerController {
24 |
25 |
26 |
27 |
28 | @Autowired
29 | private CustomerService customerService;
30 |
31 | @Autowired
32 | private PasswordEncoder passwordEncoder;
33 |
34 |
35 | @GetMapping("/hello")
36 | public String testHandler() {
37 | return "Welcome to Spring Security";
38 | }
39 |
40 |
41 | /*
42 |
43 | {
44 | "name": "ram",
45 | "email": "ram@gmail.com",
46 | "password": "1234",
47 | "address": "delhi",
48 | "authorities":[
49 | {
50 | "name": "ROLE_USER"
51 | },
52 | {
53 | "name": "ROLE_ADMIN"
54 | }
55 | ]
56 | }
57 |
58 |
59 |
60 | */
61 |
62 | @PostMapping("/customers")
63 | public ResponseEntity saveCustomerHandler(@RequestBody Customer customer){
64 |
65 |
66 | customer.setPassword(passwordEncoder.encode(customer.getPassword()));
67 |
68 | Customer registeredCustomer= customerService.registerCustomer(customer);
69 |
70 | return new ResponseEntity<>(registeredCustomer,HttpStatus.ACCEPTED);
71 |
72 | }
73 |
74 | @GetMapping("/customers/{email}")
75 | public ResponseEntity getCustomerByEmailHandler(@PathVariable("email") String email){
76 |
77 |
78 | Customer customer= customerService.getCustomerDetailsByEmail(email);
79 |
80 | return new ResponseEntity<>(customer,HttpStatus.ACCEPTED);
81 |
82 | }
83 |
84 | @GetMapping("/customers")
85 | public ResponseEntity> getAllCustomerHandler(){
86 |
87 |
88 | List customers= customerService.getAllCustomerDetails();
89 |
90 | return new ResponseEntity<>(customers,HttpStatus.ACCEPTED);
91 |
92 | }
93 |
94 |
95 |
96 | }
97 |
--------------------------------------------------------------------------------
/Spring_Security_JWT_With_Role/SpringSecurityJwtWithRole/src/main/java/com/masai/controller/LoginController.java:
--------------------------------------------------------------------------------
1 | package com.masai.controller;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.http.HttpStatus;
5 | import org.springframework.http.ResponseEntity;
6 | import org.springframework.security.authentication.BadCredentialsException;
7 | import org.springframework.security.core.Authentication;
8 | import org.springframework.web.bind.annotation.GetMapping;
9 | import org.springframework.web.bind.annotation.RestController;
10 |
11 | import com.masai.model.Customer;
12 | import com.masai.repository.CustomerRepository;
13 |
14 | @RestController
15 | public class LoginController {
16 |
17 | @Autowired
18 | private CustomerRepository customerRepository;
19 |
20 | @GetMapping("/signIn")
21 | public ResponseEntity getLoggedInCustomerDetailsHandler(Authentication auth){
22 |
23 | System.out.println(auth);
24 |
25 | Customer customer= customerRepository.findByEmail(auth.getName()).orElseThrow(() -> new BadCredentialsException("Invalid Username or password"));
26 |
27 | //to get the token in body, pass HttpServletResponse inside this method parameter
28 | // System.out.println(response.getHeaders(SecurityConstants.JWT_HEADER));
29 |
30 |
31 | return new ResponseEntity<>(customer, HttpStatus.ACCEPTED);
32 |
33 |
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/Spring_Security_JWT_With_Role/SpringSecurityJwtWithRole/src/main/java/com/masai/exception/CustomerException.java:
--------------------------------------------------------------------------------
1 | package com.masai.exception;
2 |
3 | public class CustomerException extends RuntimeException {
4 |
5 | public CustomerException() {
6 | // TODO Auto-generated constructor stub
7 | }
8 |
9 | public CustomerException(String message) {
10 | super(message);
11 | }
12 |
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/Spring_Security_JWT_With_Role/SpringSecurityJwtWithRole/src/main/java/com/masai/exception/GlobalExceptionHandler.java:
--------------------------------------------------------------------------------
1 | package com.masai.exception;
2 |
3 | import java.time.LocalDateTime;
4 |
5 | import org.springframework.http.HttpStatus;
6 | import org.springframework.http.ResponseEntity;
7 | import org.springframework.web.bind.annotation.ControllerAdvice;
8 | import org.springframework.web.bind.annotation.ExceptionHandler;
9 | import org.springframework.web.context.request.WebRequest;
10 |
11 | @ControllerAdvice
12 | public class GlobalExceptionHandler {
13 |
14 |
15 |
16 |
17 |
18 | @ExceptionHandler(CustomerException.class)
19 | public ResponseEntity customerExceptionHandler(CustomerException ce, WebRequest req){
20 |
21 |
22 | MyErrorDetails err= new MyErrorDetails();
23 | err.setTimestamp(LocalDateTime.now());
24 | err.setMessage(ce.getMessage());
25 | err.setDetails(req.getDescription(false));
26 |
27 | return new ResponseEntity(err, HttpStatus.BAD_REQUEST);
28 |
29 | }
30 |
31 |
32 |
33 | @ExceptionHandler(Exception.class)
34 | public ResponseEntity otherExceptionHandler(Exception se, WebRequest req){
35 |
36 |
37 | MyErrorDetails err= new MyErrorDetails();
38 | err.setTimestamp(LocalDateTime.now());
39 | err.setMessage(se.getMessage());
40 | err.setDetails(req.getDescription(false));
41 |
42 | return new ResponseEntity(err, HttpStatus.INTERNAL_SERVER_ERROR);
43 |
44 | }
45 |
46 |
47 |
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/Spring_Security_JWT_With_Role/SpringSecurityJwtWithRole/src/main/java/com/masai/exception/MyErrorDetails.java:
--------------------------------------------------------------------------------
1 | package com.masai.exception;
2 |
3 | import java.time.LocalDateTime;
4 |
5 | public class MyErrorDetails {
6 |
7 | private LocalDateTime timestamp;
8 | private String message;
9 | private String details;
10 |
11 |
12 | public MyErrorDetails() {
13 | // TODO Auto-generated constructor stub
14 | }
15 |
16 |
17 | public MyErrorDetails(LocalDateTime timestamp, String message, String details) {
18 | super();
19 | this.timestamp = timestamp;
20 | this.message = message;
21 | this.details = details;
22 | }
23 |
24 |
25 | public LocalDateTime getTimestamp() {
26 | return timestamp;
27 | }
28 |
29 |
30 | public void setTimestamp(LocalDateTime timestamp) {
31 | this.timestamp = timestamp;
32 | }
33 |
34 |
35 | public String getMessage() {
36 | return message;
37 | }
38 |
39 |
40 | public void setMessage(String message) {
41 | this.message = message;
42 | }
43 |
44 |
45 | public String getDetails() {
46 | return details;
47 | }
48 |
49 |
50 | public void setDetails(String details) {
51 | this.details = details;
52 | }
53 |
54 |
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/Spring_Security_JWT_With_Role/SpringSecurityJwtWithRole/src/main/java/com/masai/model/Authority.java:
--------------------------------------------------------------------------------
1 | package com.masai.model;
2 |
3 | import com.fasterxml.jackson.annotation.JsonIgnore;
4 |
5 | import jakarta.persistence.Entity;
6 | import jakarta.persistence.GeneratedValue;
7 | import jakarta.persistence.GenerationType;
8 | import jakarta.persistence.Id;
9 | import jakarta.persistence.ManyToOne;
10 | import lombok.Data;
11 | import lombok.Getter;
12 | import lombok.Setter;
13 |
14 | @Entity
15 | @Getter
16 | @Setter
17 | public class Authority {
18 |
19 |
20 | @Id
21 | @GeneratedValue(strategy = GenerationType.AUTO)
22 | private Integer authId;
23 |
24 | private String name;
25 |
26 | @JsonIgnore
27 | @ManyToOne
28 | private Customer customer;
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/Spring_Security_JWT_With_Role/SpringSecurityJwtWithRole/src/main/java/com/masai/model/Customer.java:
--------------------------------------------------------------------------------
1 | package com.masai.model;
2 |
3 | import java.util.ArrayList;
4 | import java.util.HashSet;
5 | import java.util.List;
6 | import java.util.Set;
7 |
8 | import com.fasterxml.jackson.annotation.JsonIgnore;
9 | import com.fasterxml.jackson.annotation.JsonProperty;
10 |
11 | import jakarta.persistence.CascadeType;
12 | import jakarta.persistence.Column;
13 | import jakarta.persistence.Entity;
14 | import jakarta.persistence.FetchType;
15 | import jakarta.persistence.GeneratedValue;
16 | import jakarta.persistence.GenerationType;
17 | import jakarta.persistence.Id;
18 | import jakarta.persistence.OneToMany;
19 | import lombok.Getter;
20 | import lombok.Setter;
21 |
22 | @Entity
23 | @Getter
24 | @Setter
25 | public class Customer {
26 |
27 | @Id
28 | @GeneratedValue(strategy = GenerationType.AUTO)
29 | private Integer custId;
30 | private String name;
31 |
32 | @Column(unique = true)
33 | private String email;
34 | @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
35 | private String password;
36 | private String address;
37 |
38 |
39 | @OneToMany(cascade = CascadeType.ALL, mappedBy = "customer",fetch=FetchType.EAGER)
40 | private List authorities = new ArrayList<>();
41 |
42 |
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/Spring_Security_JWT_With_Role/SpringSecurityJwtWithRole/src/main/java/com/masai/repository/CustomerRepository.java:
--------------------------------------------------------------------------------
1 | package com.masai.repository;
2 |
3 | import java.util.Optional;
4 |
5 | import org.springframework.data.jpa.repository.JpaRepository;
6 |
7 | import com.masai.model.Customer;
8 |
9 | public interface CustomerRepository extends JpaRepository{
10 |
11 |
12 | public Optional findByEmail(String email);
13 | }
14 |
--------------------------------------------------------------------------------
/Spring_Security_JWT_With_Role/SpringSecurityJwtWithRole/src/main/java/com/masai/service/CustomerService.java:
--------------------------------------------------------------------------------
1 | package com.masai.service;
2 | import java.util.List;
3 |
4 | import com.masai.exception.CustomerException;
5 | import com.masai.model.Customer;
6 |
7 | public interface CustomerService {
8 |
9 | public Customer registerCustomer(Customer customer);
10 |
11 | public Customer getCustomerDetailsByEmail(String email)throws CustomerException;
12 |
13 | public List getAllCustomerDetails()throws CustomerException;
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/Spring_Security_JWT_With_Role/SpringSecurityJwtWithRole/src/main/java/com/masai/service/CustomerServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.masai.service;
2 |
3 | import java.util.List;
4 | import java.util.Set;
5 |
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.stereotype.Service;
8 |
9 | import com.masai.exception.CustomerException;
10 | import com.masai.model.Authority;
11 | import com.masai.model.Customer;
12 | import com.masai.repository.CustomerRepository;
13 |
14 | @Service
15 | public class CustomerServiceImpl implements CustomerService{
16 |
17 | @Autowired
18 | private CustomerRepository customerRepository;
19 |
20 |
21 |
22 | @Override
23 | public Customer registerCustomer(Customer customer) throws CustomerException {
24 |
25 | List authorities= customer.getAuthorities();
26 |
27 | for(Authority authority:authorities) {
28 | authority.setCustomer(customer);
29 | }
30 |
31 | return customerRepository.save(customer);
32 |
33 |
34 | }
35 |
36 | @Override
37 | public Customer getCustomerDetailsByEmail(String email)throws CustomerException {
38 |
39 | return customerRepository.findByEmail(email).orElseThrow(() -> new CustomerException("Customer Not found with Email: "+email));
40 | }
41 |
42 | @Override
43 | public List getAllCustomerDetails()throws CustomerException {
44 |
45 | List customers= customerRepository.findAll();
46 |
47 | if(customers.isEmpty())
48 | throw new CustomerException("No Customer find");
49 |
50 | return customers;
51 |
52 | }
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/Spring_Security_JWT_With_Role/SpringSecurityJwtWithRole/src/main/java/com/masai/service/CustomerUserDetails.java:
--------------------------------------------------------------------------------
1 | package com.masai.service;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Collection;
5 | import java.util.List;
6 | import java.util.Set;
7 |
8 | import org.springframework.security.core.GrantedAuthority;
9 | import org.springframework.security.core.authority.SimpleGrantedAuthority;
10 | import org.springframework.security.core.userdetails.UserDetails;
11 | import org.springframework.stereotype.Component;
12 |
13 | import com.masai.model.Authority;
14 | import com.masai.model.Customer;
15 |
16 |
17 | public class CustomerUserDetails implements UserDetails {
18 |
19 | Customer customer;
20 |
21 |
22 |
23 |
24 | public CustomerUserDetails(Customer customer) {
25 | this.customer = customer;
26 | }
27 |
28 | @Override
29 | public Collection extends GrantedAuthority> getAuthorities() {
30 |
31 | Collection authorities=new ArrayList<>();
32 |
33 | List auths= customer.getAuthorities();
34 |
35 |
36 |
37 |
38 | for(Authority auth:auths) {
39 | SimpleGrantedAuthority simpleGrantedAuthority=new SimpleGrantedAuthority(auth.getName());
40 | authorities.add(simpleGrantedAuthority);
41 | }
42 |
43 |
44 | return authorities;
45 |
46 | }
47 |
48 | @Override
49 | public String getPassword() {
50 |
51 | return customer.getPassword();
52 | }
53 |
54 | @Override
55 | public String getUsername() {
56 | // TODO Auto-generated method stub
57 | return customer.getEmail();
58 | }
59 |
60 | @Override
61 | public boolean isAccountNonExpired() {
62 | // TODO Auto-generated method stub
63 | return true;
64 | }
65 |
66 | @Override
67 | public boolean isAccountNonLocked() {
68 | // TODO Auto-generated method stub
69 | return true;
70 | }
71 |
72 | @Override
73 | public boolean isCredentialsNonExpired() {
74 | // TODO Auto-generated method stub
75 | return true;
76 | }
77 |
78 | @Override
79 | public boolean isEnabled() {
80 | // TODO Auto-generated method stub
81 | return true;
82 | }
83 |
84 | }
85 |
--------------------------------------------------------------------------------
/Spring_Security_JWT_With_Role/SpringSecurityJwtWithRole/src/main/java/com/masai/service/CustomerUserDetailsService.java:
--------------------------------------------------------------------------------
1 | package com.masai.service;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Optional;
6 | import java.util.Set;
7 |
8 | import org.springframework.beans.factory.annotation.Autowired;
9 | import org.springframework.security.authentication.BadCredentialsException;
10 | import org.springframework.security.core.GrantedAuthority;
11 | import org.springframework.security.core.authority.AuthorityUtils;
12 | import org.springframework.security.core.authority.SimpleGrantedAuthority;
13 | import org.springframework.security.core.userdetails.User;
14 | import org.springframework.security.core.userdetails.UserDetails;
15 | import org.springframework.security.core.userdetails.UserDetailsService;
16 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
17 | import org.springframework.stereotype.Service;
18 |
19 | import com.masai.model.Authority;
20 | import com.masai.model.Customer;
21 | import com.masai.repository.CustomerRepository;
22 |
23 | @Service
24 | public class CustomerUserDetailsService implements UserDetailsService{
25 |
26 |
27 |
28 |
29 | @Autowired
30 | private CustomerRepository customerRepository;
31 |
32 |
33 | @Override
34 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
35 |
36 |
37 | Optional opt= customerRepository.findByEmail(username);
38 |
39 | if(opt.isPresent()) {
40 |
41 |
42 | //return new CustomerUserDetails(opt.get());
43 |
44 | Customer customer= opt.get();
45 |
46 | List authorities = new ArrayList<>();
47 |
48 |
49 |
50 | List auths= customer.getAuthorities();
51 |
52 | for(Authority auth:auths) {
53 | SimpleGrantedAuthority sga=new SimpleGrantedAuthority(auth.getName());
54 | System.out.println("siga "+sga);
55 | authorities.add(sga);
56 | }
57 |
58 | System.out.println("granted authorities "+authorities);
59 |
60 |
61 | return new User(customer.getEmail(), customer.getPassword(), authorities);
62 |
63 |
64 |
65 | }else
66 | throw new BadCredentialsException("User Details not found with this username: "+username);
67 |
68 |
69 |
70 |
71 |
72 | }
73 |
74 |
75 | // private List getGrantedAuthorities(Set authorities) {
76 | // List grantedAuthorities = new ArrayList<>();
77 | // for (Authority authority : authorities) {
78 | // grantedAuthorities.add(new SimpleGrantedAuthority(authority.getName()));
79 | // }
80 | // return grantedAuthorities;
81 | // }
82 |
83 | }
84 |
--------------------------------------------------------------------------------
/Spring_Security_JWT_With_Role/SpringSecurityJwtWithRole/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 |
2 | #db specific properties
3 | spring.datasource.url=jdbc:mysql://localhost:3306/masaidb
4 | spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
5 | spring.datasource.username=root
6 | spring.datasource.password=root
7 |
8 | #ORM s/w specific properties
9 | spring.jpa.hibernate.ddl-auto=update
10 | spring.jpa.show-sql=true
11 |
12 | #spring.security.user.name=ratan
13 | #spring.security.user.password=123
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/Spring_Security_JWT_With_Role/SpringSecurityJwtWithRole/src/test/java/com/masai/SpringSecurityJwtWithRoleApplicationTests.java:
--------------------------------------------------------------------------------
1 | package com.masai;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.springframework.boot.test.context.SpringBootTest;
5 |
6 | @SpringBootTest
7 | class SpringSecurityJwtWithRoleApplicationTests {
8 |
9 | @Test
10 | void contextLoads() {
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/Spring_Security_With_CustomAthenticationProvider/.gitignore:
--------------------------------------------------------------------------------
1 | HELP.md
2 | target/
3 | !.mvn/wrapper/maven-wrapper.jar
4 | !**/src/main/**/target/
5 | !**/src/test/**/target/
6 |
7 | ### STS ###
8 | .apt_generated
9 | .classpath
10 | .factorypath
11 | .project
12 | .settings
13 | .springBeans
14 | .sts4-cache
15 |
16 | ### IntelliJ IDEA ###
17 | .idea
18 | *.iws
19 | *.iml
20 | *.ipr
21 |
22 | ### NetBeans ###
23 | /nbproject/private/
24 | /nbbuild/
25 | /dist/
26 | /nbdist/
27 | /.nb-gradle/
28 | build/
29 | !**/src/main/**/build/
30 | !**/src/test/**/build/
31 |
32 | ### VS Code ###
33 | .vscode/
34 |
--------------------------------------------------------------------------------
/Spring_Security_With_CustomAthenticationProvider/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Shubh2-0/Spring_Security/a0d45807af1cd2b3f178a105f9b61b8bfaa7c8b6/Spring_Security_With_CustomAthenticationProvider/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/Spring_Security_With_CustomAthenticationProvider/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.3/apache-maven-3.9.3-bin.zip
2 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar
3 |
--------------------------------------------------------------------------------
/Spring_Security_With_CustomAthenticationProvider/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | org.springframework.boot
8 | spring-boot-starter-parent
9 | 3.1.1
10 |
11 |
12 | com.masai
13 | Spring_Security_Without_JWT
14 | 0.0.1-SNAPSHOT
15 | Spring_Security_Without_JWT
16 | Demo project for Spring Boot Security Without JWT
17 |
18 | 17
19 |
20 |
21 |
22 | org.springframework.boot
23 | spring-boot-starter-data-jpa
24 |
25 |
26 | org.springframework.boot
27 | spring-boot-starter-security
28 |
29 |
30 | org.springframework.boot
31 | spring-boot-starter-web
32 |
33 |
34 |
35 | org.springframework.boot
36 | spring-boot-devtools
37 | runtime
38 | true
39 |
40 |
41 | com.mysql
42 | mysql-connector-j
43 | runtime
44 |
45 |
46 | org.projectlombok
47 | lombok
48 | true
49 |
50 |
51 | org.springframework.boot
52 | spring-boot-starter-test
53 | test
54 |
55 |
56 | org.springframework.boot
57 | spring-boot-starter-security
58 |
59 |
60 | org.springframework.security
61 | spring-security-test
62 | test
63 |
64 |
65 |
66 |
67 |
68 |
69 | org.springframework.boot
70 | spring-boot-maven-plugin
71 |
72 |
73 |
74 | org.projectlombok
75 | lombok
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
--------------------------------------------------------------------------------
/Spring_Security_With_CustomAthenticationProvider/src/main/java/com/masai/SpringSecurityWithoutJwtApplication.java:
--------------------------------------------------------------------------------
1 | package com.masai;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class SpringSecurityWithoutJwtApplication {
8 |
9 | /*
10 | * MAIN INTERFACE WHERE OUR APPLICATION IS STARTED THIS CLASS BY DEFAULT CREATED
11 | * BY SPRING BOOT
12 | */
13 |
14 | public static void main(String[] args) {
15 | SpringApplication.run(SpringSecurityWithoutJwtApplication.class, args);
16 | }
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/Spring_Security_With_CustomAthenticationProvider/src/main/java/com/masai/config/AppConfig.java:
--------------------------------------------------------------------------------
1 | package com.masai.config;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.Configuration;
5 | import org.springframework.http.HttpMethod;
6 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
7 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
8 | import org.springframework.security.crypto.password.PasswordEncoder;
9 | import org.springframework.security.web.SecurityFilterChain;
10 |
11 | @Configuration
12 | public class AppConfig {
13 |
14 | /*
15 | * HERE WE CREATE OUR OWN SECURITY CHAIN FILTER THAT AUTHENTICATES THE USER
16 | * MEANS HERE WE CUSTOMIZE THE CONFIGURATION AND ALSO HERE WE USE @Bean
17 | * ANNOTATION SO IT'S SHOULD REGISTOR WITH THE SPRING CONTAINER
18 | */
19 | @Bean
20 | public SecurityFilterChain springSecurityConfiguration(HttpSecurity http) throws Exception {
21 |
22 | /*
23 | * HERE OUR ALL THE REQUEST IS AUTHORISED
24 | */
25 | http.authorizeHttpRequests()
26 | /*
27 | * HERE WE GIVE THAT PARTICULAR END POINT(APIs) TO ACCESS ANYONE MEANS THIS API
28 | * BY AUTHORISED CLIENTS ALSO AND UNAUTHORISED CLIENT ALSO WHITE LISTING THIS
29 | * API IF WE HAVE TWO END POINTS WITH SAME NAME BUT DIFFERENT GETTING METHOD SO
30 | * WE HAVE GIVE THE TYPE ALSO
31 | */
32 | .requestMatchers("/customers").permitAll()
33 | /*
34 | * HERE WE GIVE END ALL THE POINT(APIs)[NOT INCLUDE THAT APIs WHERE WE GIVE
35 | * .permillAll() ] TO ACCESS BY AUTHORISED CLIENTS ONLY
36 | */
37 | .anyRequest().authenticated()
38 | /*
39 | * SOME EXTRA INFORMATION OR SECURITY FEATURES
40 | */
41 | .and()
42 | /*
43 | * HERE WE DISABLE THE csrf (Cross-Site Request Forgery) IF WE EBBALED THE
44 | * SPRING SECURITY FEATURE IN OUR APPLICATION IT WILL STOP ANY KIND OF POST
45 | * REQUEST AND PUT REQUEST WHICH WILL SHARE SOME DATA BY DEFUALT IT IS ENBLED IN
46 | * THE SPRING SECURITY BUT WE HAVE TO DISABLED THIS
47 | */
48 | .csrf().disable()
49 | /*
50 | * THIS IS BASICALLY USED FOR WEB BROSWER WHERE WE CAN SEE THE LOGIN PAGE WHICH
51 | * IS AUTOMATICALLY CREATED BY SPRING SECURITY
52 | */
53 | .formLogin().and()
54 | /*
55 | * THIS IS BASICALLY USE FOR POSTMEN AND SOME JAVASCRIPT
56 | */
57 | .httpBasic();
58 |
59 | /*
60 | * THIS STATEMENT WILL RETURN THE SECURITY CHAIN OBJECT
61 | */
62 | return http.build();
63 |
64 | }
65 |
66 | /*
67 | * HERE THIS METHOD IS RESponSiBLe fOR RETURNING THE PasswordEncoder OBJECT
68 | * WHERE WE CONVERTED THE USER PASSWORD INTO Base64 Encoded VERSION AND ALSO
69 | * HERE WE USE @Bean ANNOTATION SO IT'S SHOULD REGISTOR WITH THE SPRING
70 | * CONTAINER
71 | */
72 | @Bean
73 | public PasswordEncoder passwordEncoder() {
74 |
75 | return new BCryptPasswordEncoder();
76 | }
77 |
78 | }
79 |
--------------------------------------------------------------------------------
/Spring_Security_With_CustomAthenticationProvider/src/main/java/com/masai/controller/CustomerController.java:
--------------------------------------------------------------------------------
1 | package com.masai.controller;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.http.HttpStatus;
7 | import org.springframework.http.ResponseEntity;
8 | import org.springframework.security.crypto.password.PasswordEncoder;
9 | import org.springframework.web.bind.annotation.GetMapping;
10 | import org.springframework.web.bind.annotation.PathVariable;
11 | import org.springframework.web.bind.annotation.PostMapping;
12 | import org.springframework.web.bind.annotation.RequestBody;
13 | import org.springframework.web.bind.annotation.RestController;
14 |
15 | import com.masai.exception.CustomerException;
16 | import com.masai.model.Customer;
17 | import com.masai.service.CustomerService;
18 |
19 | /*
20 | OUR RESTCONTROLLER WHERE WE CREATE
21 | ENDPOINTS(APIs)
22 | */
23 |
24 | @RestController
25 | public class CustomerController {
26 |
27 | @Autowired
28 | private CustomerService customerService;
29 |
30 | /*
31 | * THIS OBJECT IS RESPONSIBLE FOR CONVERTED THE USER PASSWORD INTO base64
32 | * ENCODED VERSION
33 | */
34 | @Autowired
35 | private PasswordEncoder passwordEncoder;
36 |
37 | @GetMapping("/learn")
38 | public String testHandler() {
39 |
40 | return "LEARNING SPRING SECURITY";
41 |
42 | }
43 |
44 | @PostMapping("/customers")
45 | public ResponseEntity addCustomerHandler(@RequestBody Customer customer) throws CustomerException {
46 |
47 | // HERE WE CHANGE THE NORMAL USER PASSWORD INTO base64 encoded VERSION
48 | customer.setPassword(passwordEncoder.encode(customer.getPassword()));
49 |
50 | Customer registorCustomer = customerService.addCustomer(customer);
51 |
52 | return new ResponseEntity(registorCustomer, HttpStatus.ACCEPTED);
53 |
54 | }
55 |
56 | @GetMapping("/customers/{email}")
57 | public ResponseEntity getCustomerbyEmailHandler(@PathVariable("email") String email)
58 | throws CustomerException {
59 |
60 | return new ResponseEntity(customerService.getCustomerByEmail(email), HttpStatus.ACCEPTED);
61 |
62 | }
63 |
64 | @GetMapping("/customers/all")
65 | public ResponseEntity> getAllCustomerHandler() throws CustomerException {
66 |
67 | return new ResponseEntity>(customerService.getAllCustomer(), HttpStatus.ACCEPTED);
68 |
69 | }
70 |
71 | @GetMapping("/customers/address/{address}")
72 | public ResponseEntity> getAllCustomerByAddressHandler(@PathVariable ("address") String address ) throws CustomerException{
73 |
74 | return new ResponseEntity>(customerService.getCustomerByAddress(address), HttpStatus.ACCEPTED);
75 | }
76 |
77 | }
78 |
--------------------------------------------------------------------------------
/Spring_Security_With_CustomAthenticationProvider/src/main/java/com/masai/controller/CustomerLoginController.java:
--------------------------------------------------------------------------------
1 | package com.masai.controller;
2 |
3 |
4 | import org.springframework.beans.factory.annotation.Autowired;
5 | import org.springframework.http.HttpStatus;
6 | import org.springframework.http.ResponseEntity;
7 | import org.springframework.security.authentication.BadCredentialsException;
8 | import org.springframework.security.core.Authentication;
9 | import org.springframework.web.bind.annotation.GetMapping;
10 | import org.springframework.web.bind.annotation.RestController;
11 |
12 | import com.masai.model.Customer;
13 | import com.masai.repository.CustomerRepository;
14 |
15 | @RestController
16 | public class CustomerLoginController {
17 |
18 | @Autowired
19 | private CustomerRepository customerRepository;
20 |
21 |
22 | /*
23 | * HERE WE CREATED ONE ENDPOINT FOR signIn THE USER
24 | * IT WILL TAKE Authentication object
25 | * IN Authentication object WE HAVE THE USERNAME AND PASSWORD OF THE USER
26 | * IN WHICH WE CAN FIND THE USER BY THIER USERNAME
27 | */
28 | @GetMapping("/signIn")
29 | public ResponseEntity getLoggedInCustomerHandler(Authentication auth){
30 |
31 | System.out.println("AUTHENTICATION OBJECT :"+ auth);
32 |
33 | /* IN Authentication object WE HAVE SOME METHOD WHERE WE CAN ACCESS THE USER INFORMATION
34 | * ONE OF THEM ARE getName() WHICH BASICALLY return THE USER username
35 | *
36 | */
37 | Customer customer = customerRepository.findByEmail(auth.getName()).orElseThrow((() -> new BadCredentialsException("invalid email")));
38 |
39 |
40 | return new ResponseEntity(customer,HttpStatus.ACCEPTED);
41 |
42 | }
43 |
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/Spring_Security_With_CustomAthenticationProvider/src/main/java/com/masai/exception/CustomError.java:
--------------------------------------------------------------------------------
1 | package com.masai.exception;
2 |
3 | import java.time.LocalDateTime;
4 |
5 | import lombok.AllArgsConstructor;
6 | import lombok.Data;
7 | import lombok.NoArgsConstructor;
8 |
9 | @Data
10 | @NoArgsConstructor
11 | @AllArgsConstructor
12 |
13 | /*
14 | * HERE WE CREATED OUR OWN CUSTOME EXCEPTION OR ERROR IN SIMPLE BODY OF OUR
15 | * ERROR
16 | */
17 | public class CustomError {
18 |
19 | private LocalDateTime time;
20 | private String message;
21 | private String details;
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/Spring_Security_With_CustomAthenticationProvider/src/main/java/com/masai/exception/CustomerException.java:
--------------------------------------------------------------------------------
1 | package com.masai.exception;
2 |
3 | public class CustomerException extends Exception {
4 |
5 | public CustomerException(String m) {
6 |
7 | super(m);
8 | }
9 |
10 | }
11 |
--------------------------------------------------------------------------------
/Spring_Security_With_CustomAthenticationProvider/src/main/java/com/masai/exception/GlobalExceptionHandler.java:
--------------------------------------------------------------------------------
1 | package com.masai.exception;
2 |
3 | import java.time.LocalDateTime;
4 |
5 | import org.springframework.http.HttpStatus;
6 | import org.springframework.http.ResponseEntity;
7 | import org.springframework.web.bind.annotation.ControllerAdvice;
8 | import org.springframework.web.bind.annotation.ExceptionHandler;
9 | import org.springframework.web.context.request.WebRequest;
10 |
11 | @ControllerAdvice
12 | public class GlobalExceptionHandler {
13 |
14 | /*
15 | * HERE WE CREATE OUR OWN CUSTOME ERROR SO WHEN ANY EEXCEPTION ACCUR SO THAT
16 | * EXCEPTION HANDLER HANDLE THAT SITUATION
17 | *
18 | */
19 | @ExceptionHandler(CustomerException.class)
20 | public ResponseEntity customerExceptionHandler(CustomerException e, WebRequest req) {
21 |
22 | CustomError error = new CustomError();
23 | error.setTime(LocalDateTime.now());
24 | error.setMessage(e.getMessage());
25 | error.setDetails(req.getDescription(false));
26 |
27 | return new ResponseEntity(error, HttpStatus.BAD_REQUEST);
28 |
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/Spring_Security_With_CustomAthenticationProvider/src/main/java/com/masai/model/Customer.java:
--------------------------------------------------------------------------------
1 | package com.masai.model;
2 |
3 | import com.fasterxml.jackson.annotation.JsonProperty;
4 |
5 | import jakarta.annotation.Generated;
6 | import jakarta.persistence.Column;
7 | import jakarta.persistence.Entity;
8 | import jakarta.persistence.GeneratedValue;
9 | import jakarta.persistence.GenerationType;
10 | import jakarta.persistence.Id;
11 | import lombok.AllArgsConstructor;
12 | import lombok.Data;
13 | import lombok.NoArgsConstructor;
14 |
15 | @Entity
16 | @Data
17 | @NoArgsConstructor
18 | @AllArgsConstructor
19 | public class Customer {
20 |
21 | @Id
22 | @GeneratedValue(strategy = GenerationType.AUTO)
23 | private Integer Id;
24 |
25 | private String name;
26 |
27 | @Column(unique = true)
28 | private String email;
29 |
30 | /*
31 | * AT THE TIME OF FETCHING ANY USER WE CAN'T SEE THIER PASSWORD BECUASE OF THIS
32 | * PROPERTY
33 | */
34 | @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
35 | private String password;
36 |
37 | private String address;
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/Spring_Security_With_CustomAthenticationProvider/src/main/java/com/masai/repository/CustomerRepository.java:
--------------------------------------------------------------------------------
1 | package com.masai.repository;
2 |
3 | import java.util.List;
4 | import java.util.Optional;
5 |
6 | import org.springframework.data.jpa.repository.JpaRepository;
7 |
8 | import com.masai.model.Customer;
9 |
10 | public interface CustomerRepository extends JpaRepository {
11 |
12 | /*
13 | * HERE WE CREATE A METHOD WHERE WE CAN FIND THE USER BY THIER EMAIL ADDRESS AND
14 | * ALSO HERE WE USE Optional CLAS FOR ACCHIEVING THE FUNCTIONAL WAY
15 | */
16 | public Optional findByEmail(String email);
17 |
18 | /*
19 | * HERE WE CREATE A METHOD WHERE WE CAN FIND THE USER BY THIER ADDRESS ALSO
20 | */
21 | public Optional> findByAddress(String address);
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/Spring_Security_With_CustomAthenticationProvider/src/main/java/com/masai/service/CustomerService.java:
--------------------------------------------------------------------------------
1 | package com.masai.service;
2 |
3 | import java.util.List;
4 |
5 | import com.masai.exception.CustomerException;
6 | import com.masai.model.Customer;
7 |
8 | public interface CustomerService {
9 |
10 | Customer addCustomer(Customer customer) throws CustomerException;
11 |
12 | Customer getCustomerByEmail(String email) throws CustomerException;
13 |
14 | List getAllCustomer() throws CustomerException;
15 |
16 | List getCustomerByAddress(String address) throws CustomerException;
17 | }
18 |
--------------------------------------------------------------------------------
/Spring_Security_With_CustomAthenticationProvider/src/main/java/com/masai/service/CustomerServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.masai.service;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.stereotype.Service;
7 |
8 | import com.masai.exception.CustomerException;
9 | import com.masai.model.Customer;
10 | import com.masai.repository.CustomerRepository;
11 |
12 | @Service
13 | public class CustomerServiceImpl implements CustomerService {
14 |
15 | @Autowired
16 | private CustomerRepository customerRepository;
17 |
18 | @Override
19 | public Customer addCustomer(Customer customer) throws CustomerException {
20 |
21 | return customerRepository.save(customer);
22 |
23 | }
24 |
25 | @Override
26 | public Customer getCustomerByEmail(String email) throws CustomerException {
27 |
28 | /*
29 | * HERE WE USE FUNCTIONAL WHY TO RETURN THE CUSTOMER OBJECT IT'S POSSIBLE BY THE
30 | * HELP OF Optional CLASS IF THE OPTIONAL IS NOT EMPTY THAN IT RETURN THE
31 | * CUSTOMER OBJECT OTHER WISE IT THROW THE CustomerException IT ISE VERY SIMPLE
32 | * AND EASY
33 | *
34 | */
35 | return customerRepository.findByEmail(email)
36 | .orElseThrow(() -> new CustomerException("Customer not found by this email : " + email));
37 |
38 | }
39 |
40 | @Override
41 | public List getAllCustomer() throws CustomerException {
42 |
43 | List customers = customerRepository.findAll();
44 |
45 | if (customers.isEmpty())
46 | throw new CustomerException("no customer found");
47 |
48 | return customers;
49 |
50 | }
51 |
52 | @Override
53 | public List getCustomerByAddress(String address) throws CustomerException {
54 |
55 | return customerRepository.findByAddress(address)
56 | .orElseThrow(() -> new CustomerException("No customer found we that address :" + address));
57 |
58 | }
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/Spring_Security_With_CustomAthenticationProvider/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | #db specific properties
2 | spring.datasource.url=jdbc:mysql://localhost:3306/prac
3 | spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
4 | spring.datasource.username=root
5 | spring.datasource.password=root
6 |
7 | #ORM s/w specific properties
8 | spring.jpa.hibernate.ddl-auto=update
9 | spring.jpa.show-sql=true
--------------------------------------------------------------------------------
/Spring_Security_With_CustomAthenticationProvider/src/test/java/com/masai/SpringSecurityWithoutJwtApplicationTests.java:
--------------------------------------------------------------------------------
1 | package com.masai;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.springframework.boot.test.context.SpringBootTest;
5 |
6 | @SpringBootTest
7 | class SpringSecurityWithoutJwtApplicationTests {
8 |
9 | @Test
10 | void contextLoads() {
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT/.gitignore:
--------------------------------------------------------------------------------
1 | HELP.md
2 | target/
3 | !.mvn/wrapper/maven-wrapper.jar
4 | !**/src/main/**/target/
5 | !**/src/test/**/target/
6 |
7 | ### STS ###
8 | .apt_generated
9 | .classpath
10 | .factorypath
11 | .project
12 | .settings
13 | .springBeans
14 | .sts4-cache
15 |
16 | ### IntelliJ IDEA ###
17 | .idea
18 | *.iws
19 | *.iml
20 | *.ipr
21 |
22 | ### NetBeans ###
23 | /nbproject/private/
24 | /nbbuild/
25 | /dist/
26 | /nbdist/
27 | /.nb-gradle/
28 | build/
29 | !**/src/main/**/build/
30 | !**/src/test/**/build/
31 |
32 | ### VS Code ###
33 | .vscode/
34 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Shubh2-0/Spring_Security/a0d45807af1cd2b3f178a105f9b61b8bfaa7c8b6/Spring_Security_With_JWT/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/Spring_Security_With_JWT/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.3/apache-maven-3.9.3-bin.zip
2 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar
3 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT/src/main/java/com/masai/SpringSecurityWithoutJwtApplication.java:
--------------------------------------------------------------------------------
1 | package com.masai;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class SpringSecurityWithoutJwtApplication {
8 |
9 | /*
10 | * MAIN INTERFACE WHERE OUR APPLICATION IS STARTED THIS CLASS BY DEFAULT CREATED
11 | * BY SPRING BOOT
12 | */
13 |
14 | public static void main(String[] args) {
15 | SpringApplication.run(SpringSecurityWithoutJwtApplication.class, args);
16 | }
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT/src/main/java/com/masai/config/AppConfig.java:
--------------------------------------------------------------------------------
1 | package com.masai.config;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.Configuration;
5 | import org.springframework.http.HttpMethod;
6 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
7 | import org.springframework.security.config.http.SessionCreationPolicy;
8 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
9 | import org.springframework.security.crypto.password.PasswordEncoder;
10 | import org.springframework.security.web.SecurityFilterChain;
11 | import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
12 |
13 | @Configuration
14 | public class AppConfig {
15 |
16 | @Bean
17 | public SecurityFilterChain springSecurityConfiguration(HttpSecurity http) throws Exception {
18 |
19 | http
20 | .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
21 | .and()
22 | .csrf().disable()
23 | .authorizeHttpRequests()
24 | .requestMatchers(HttpMethod.POST, "/customers").permitAll()
25 | .anyRequest().authenticated().and()
26 | .addFilterAfter(new JwtTokenGeneratorFilter(), BasicAuthenticationFilter.class)
27 | .addFilterBefore(new JwtTokenValidatorFilter(), BasicAuthenticationFilter.class)
28 | .formLogin()
29 | .and()
30 | .httpBasic();
31 |
32 | return http.build();
33 |
34 | }
35 |
36 | @Bean
37 | public PasswordEncoder passwordEncoder() {
38 |
39 | return new BCryptPasswordEncoder();
40 |
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT/src/main/java/com/masai/config/JwtTokenGeneratorFilter.java:
--------------------------------------------------------------------------------
1 | package com.masai.config;
2 |
3 | import java.io.IOException;
4 |
5 | import javax.crypto.SecretKey;
6 |
7 | import org.springframework.security.core.Authentication;
8 | import org.springframework.web.filter.OncePerRequestFilter;
9 |
10 | import jakarta.servlet.FilterChain;
11 | import jakarta.servlet.ServletException;
12 | import jakarta.servlet.http.HttpServletRequest;
13 | import jakarta.servlet.http.HttpServletResponse;
14 |
15 |
16 | import java.util.Collection;
17 | import java.util.Date;
18 | import java.util.HashSet;
19 | import java.util.Set;
20 |
21 |
22 |
23 | import org.springframework.security.core.GrantedAuthority;
24 | import org.springframework.security.core.context.SecurityContextHolder;
25 | import io.jsonwebtoken.Jwts;
26 | import io.jsonwebtoken.security.Keys;
27 |
28 |
29 | public class JwtTokenGeneratorFilter extends OncePerRequestFilter {
30 |
31 | @Override
32 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
33 | throws ServletException, IOException {
34 |
35 | System.out.println("inside doFilter....");
36 |
37 | Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
38 | if (null != authentication) {
39 |
40 | SecretKey key = Keys.hmacShaKeyFor(SecurityConstants.JWT_KEY.getBytes());
41 |
42 | String jwt = Jwts.builder()
43 | .setIssuer("Ratan")
44 | .setSubject("JWT Token")
45 | .claim("username", authentication.getName())
46 | .claim("authorities", populateAuthorities(authentication.getAuthorities()))
47 | .setIssuedAt(new Date())
48 | .setExpiration(new Date(new Date().getTime()+ 30000000)) // expiration time of 8 hours
49 | .signWith(key).compact();
50 |
51 | response.setHeader(SecurityConstants.JWT_HEADER, jwt);
52 |
53 |
54 |
55 | }
56 |
57 | filterChain.doFilter(request, response);
58 |
59 |
60 |
61 | }
62 |
63 |
64 |
65 |
66 | private String populateAuthorities(Collection extends GrantedAuthority> collection) {
67 |
68 | Set authoritiesSet = new HashSet<>();
69 |
70 | for (GrantedAuthority authority : collection) {
71 | authoritiesSet.add(authority.getAuthority());
72 | }
73 | return String.join(",", authoritiesSet);
74 |
75 |
76 | }
77 |
78 |
79 |
80 |
81 | //this make sure that this filter will execute only for first time when client call the api /login at first time
82 | @Override
83 | protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
84 |
85 | return !request.getServletPath().equals("/signIn");
86 | }
87 |
88 |
89 | }
90 |
91 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT/src/main/java/com/masai/config/SecurityConstants.java:
--------------------------------------------------------------------------------
1 | package com.masai.config;
2 |
3 | public interface SecurityConstants {
4 |
5 | public static final String JWT_KEY ="ddsmdskjsmdskkljnssmscsccdcdd";
6 | public static final String JWT_HEADER="Authorization";
7 |
8 | }
9 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT/src/main/java/com/masai/controller/CustomerController.java:
--------------------------------------------------------------------------------
1 | package com.masai.controller;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.http.HttpStatus;
7 | import org.springframework.http.ResponseEntity;
8 | import org.springframework.security.crypto.password.PasswordEncoder;
9 | import org.springframework.web.bind.annotation.GetMapping;
10 | import org.springframework.web.bind.annotation.PathVariable;
11 | import org.springframework.web.bind.annotation.PostMapping;
12 | import org.springframework.web.bind.annotation.RequestBody;
13 | import org.springframework.web.bind.annotation.RestController;
14 |
15 | import com.masai.exception.CustomerException;
16 | import com.masai.model.Customer;
17 | import com.masai.service.CustomerService;
18 |
19 | /*
20 | OUR RESTCONTROLLER WHERE WE CREATE
21 | ENDPOINTS(APIs)
22 | */
23 |
24 | @RestController
25 | public class CustomerController {
26 |
27 | @Autowired
28 | private CustomerService customerService;
29 |
30 | /*
31 | * THIS OBJECT IS RESPONSIBLE FOR CONVERTED THE USER PASSWORD INTO base64
32 | * ENCODED VERSION
33 | */
34 | @Autowired
35 | private PasswordEncoder passwordEncoder;
36 |
37 | @GetMapping("/learn")
38 | public String testHandler() {
39 |
40 | return "LEARNING SPRING SECURITY";
41 |
42 | }
43 |
44 | @PostMapping("/customers")
45 | public ResponseEntity addCustomerHandler(@RequestBody Customer customer) throws CustomerException {
46 |
47 | // HERE WE CHANGE THE NORMAL USER PASSWORD INTO base64 encoded VERSION
48 | customer.setPassword(passwordEncoder.encode(customer.getPassword()));
49 |
50 | Customer registorCustomer = customerService.addCustomer(customer);
51 |
52 | return new ResponseEntity(registorCustomer, HttpStatus.ACCEPTED);
53 |
54 | }
55 |
56 | @GetMapping("/customers/{email}")
57 | public ResponseEntity getCustomerbyEmailHandler(@PathVariable("email") String email)
58 | throws CustomerException {
59 |
60 | return new ResponseEntity(customerService.getCustomerByEmail(email), HttpStatus.ACCEPTED);
61 |
62 | }
63 |
64 | @GetMapping("/customers/all")
65 | public ResponseEntity> getAllCustomerHandler() throws CustomerException {
66 |
67 | return new ResponseEntity>(customerService.getAllCustomer(), HttpStatus.ACCEPTED);
68 |
69 | }
70 |
71 | @GetMapping("/customers/address/{address}")
72 | public ResponseEntity> getAllCustomerByAddressHandler(@PathVariable ("address") String address ) throws CustomerException{
73 |
74 | return new ResponseEntity>(customerService.getCustomerByAddress(address), HttpStatus.ACCEPTED);
75 | }
76 |
77 | }
78 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT/src/main/java/com/masai/controller/CustomerLoginController.java:
--------------------------------------------------------------------------------
1 | package com.masai.controller;
2 |
3 |
4 | import org.springframework.beans.factory.annotation.Autowired;
5 | import org.springframework.http.HttpStatus;
6 | import org.springframework.http.ResponseEntity;
7 | import org.springframework.security.authentication.BadCredentialsException;
8 | import org.springframework.security.core.Authentication;
9 | import org.springframework.web.bind.annotation.GetMapping;
10 | import org.springframework.web.bind.annotation.RestController;
11 |
12 | import com.masai.model.Customer;
13 | import com.masai.repository.CustomerRepository;
14 |
15 | @RestController
16 | public class CustomerLoginController {
17 |
18 | @Autowired
19 | private CustomerRepository customerRepository;
20 |
21 |
22 | /*
23 | * HERE WE CREATED ONE ENDPOINT FOR signIn THE USER
24 | * IT WILL TAKE Authentication object
25 | * IN Authentication object WE HAVE THE USERNAME AND PASSWORD OF THE USER
26 | * IN WHICH WE CAN FIND THE USER BY THIER USERNAME
27 | */
28 | @GetMapping("/signIn")
29 | public ResponseEntity getLoggedInCustomerHandler(Authentication auth){
30 |
31 | System.out.println("AUTHENTICATION OBJECT :"+ auth);
32 |
33 | /* IN Authentication object WE HAVE SOME METHOD WHERE WE CAN ACCESS THE USER INFORMATION
34 | * ONE OF THEM ARE getName() WHICH BASICALLY return THE USER username
35 | *
36 | */
37 | Customer customer = customerRepository.findByEmail(auth.getName()).orElseThrow((() -> new BadCredentialsException("invalid email")));
38 |
39 |
40 | return new ResponseEntity(customer,HttpStatus.ACCEPTED);
41 |
42 | }
43 |
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT/src/main/java/com/masai/exception/CustomError.java:
--------------------------------------------------------------------------------
1 | package com.masai.exception;
2 |
3 | import java.time.LocalDateTime;
4 |
5 | import lombok.AllArgsConstructor;
6 | import lombok.Data;
7 | import lombok.NoArgsConstructor;
8 |
9 | @Data
10 | @NoArgsConstructor
11 | @AllArgsConstructor
12 |
13 | /*
14 | * HERE WE CREATED OUR OWN CUSTOME EXCEPTION OR ERROR IN SIMPLE BODY OF OUR
15 | * ERROR
16 | */
17 | public class CustomError {
18 |
19 | private LocalDateTime time;
20 | private String message;
21 | private String details;
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT/src/main/java/com/masai/exception/CustomerException.java:
--------------------------------------------------------------------------------
1 | package com.masai.exception;
2 |
3 | public class CustomerException extends Exception {
4 |
5 | public CustomerException(String m) {
6 |
7 | super(m);
8 | }
9 |
10 | }
11 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT/src/main/java/com/masai/exception/GlobalExceptionHandler.java:
--------------------------------------------------------------------------------
1 | package com.masai.exception;
2 |
3 | import java.time.LocalDateTime;
4 |
5 | import org.springframework.http.HttpStatus;
6 | import org.springframework.http.ResponseEntity;
7 | import org.springframework.web.bind.annotation.ControllerAdvice;
8 | import org.springframework.web.bind.annotation.ExceptionHandler;
9 | import org.springframework.web.context.request.WebRequest;
10 |
11 | @ControllerAdvice
12 | public class GlobalExceptionHandler {
13 |
14 | /*
15 | * HERE WE CREATE OUR OWN CUSTOME ERROR SO WHEN ANY EEXCEPTION ACCUR SO THAT
16 | * EXCEPTION HANDLER HANDLE THAT SITUATION
17 | *
18 | */
19 | @ExceptionHandler(CustomerException.class)
20 | public ResponseEntity customerExceptionHandler(CustomerException e, WebRequest req) {
21 |
22 | CustomError error = new CustomError();
23 | error.setTime(LocalDateTime.now());
24 | error.setMessage(e.getMessage());
25 | error.setDetails(req.getDescription(false));
26 |
27 | return new ResponseEntity(error, HttpStatus.BAD_REQUEST);
28 |
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT/src/main/java/com/masai/model/Customer.java:
--------------------------------------------------------------------------------
1 | package com.masai.model;
2 |
3 | import com.fasterxml.jackson.annotation.JsonProperty;
4 |
5 | import jakarta.annotation.Generated;
6 | import jakarta.persistence.Column;
7 | import jakarta.persistence.Entity;
8 | import jakarta.persistence.GeneratedValue;
9 | import jakarta.persistence.GenerationType;
10 | import jakarta.persistence.Id;
11 | import lombok.AllArgsConstructor;
12 | import lombok.Data;
13 | import lombok.NoArgsConstructor;
14 |
15 | @Entity
16 | @Data
17 | @NoArgsConstructor
18 | @AllArgsConstructor
19 | public class Customer {
20 |
21 | @Id
22 | @GeneratedValue(strategy = GenerationType.AUTO)
23 | private Integer Id;
24 |
25 | private String name;
26 |
27 | @Column(unique = true)
28 | private String email;
29 |
30 | /*
31 | * AT THE TIME OF FETCHING ANY USER WE CAN'T SEE THIER PASSWORD BECUASE OF THIS
32 | * PROPERTY
33 | */
34 | @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
35 | private String password;
36 |
37 | private String address;
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT/src/main/java/com/masai/repository/CustomerRepository.java:
--------------------------------------------------------------------------------
1 | package com.masai.repository;
2 |
3 | import java.util.List;
4 | import java.util.Optional;
5 |
6 | import org.springframework.data.jpa.repository.JpaRepository;
7 |
8 | import com.masai.model.Customer;
9 |
10 | public interface CustomerRepository extends JpaRepository {
11 |
12 | /*
13 | * HERE WE CREATE A METHOD WHERE WE CAN FIND THE USER BY THIER EMAIL ADDRESS AND
14 | * ALSO HERE WE USE Optional CLAS FOR ACCHIEVING THE FUNCTIONAL WAY
15 | */
16 | public Optional findByEmail(String email);
17 |
18 | /*
19 | * HERE WE CREATE A METHOD WHERE WE CAN FIND THE USER BY THIER ADDRESS ALSO
20 | */
21 | public Optional> findByAddress(String address);
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT/src/main/java/com/masai/service/CustomerService.java:
--------------------------------------------------------------------------------
1 | package com.masai.service;
2 |
3 | import java.util.List;
4 |
5 | import com.masai.exception.CustomerException;
6 | import com.masai.model.Customer;
7 |
8 | public interface CustomerService {
9 |
10 | Customer addCustomer(Customer customer) throws CustomerException;
11 |
12 | Customer getCustomerByEmail(String email) throws CustomerException;
13 |
14 | List getAllCustomer() throws CustomerException;
15 |
16 | List getCustomerByAddress(String address) throws CustomerException;
17 | }
18 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT/src/main/java/com/masai/service/CustomerServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.masai.service;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.stereotype.Service;
7 |
8 | import com.masai.exception.CustomerException;
9 | import com.masai.model.Customer;
10 | import com.masai.repository.CustomerRepository;
11 |
12 | @Service
13 | public class CustomerServiceImpl implements CustomerService {
14 |
15 | @Autowired
16 | private CustomerRepository customerRepository;
17 |
18 | @Override
19 | public Customer addCustomer(Customer customer) throws CustomerException {
20 |
21 | return customerRepository.save(customer);
22 |
23 | }
24 |
25 | @Override
26 | public Customer getCustomerByEmail(String email) throws CustomerException {
27 |
28 | /*
29 | * HERE WE USE FUNCTIONAL WHY TO RETURN THE CUSTOMER OBJECT IT'S POSSIBLE BY THE
30 | * HELP OF Optional CLASS IF THE OPTIONAL IS NOT EMPTY THAN IT RETURN THE
31 | * CUSTOMER OBJECT OTHER WISE IT THROW THE CustomerException IT ISE VERY SIMPLE
32 | * AND EASY
33 | *
34 | */
35 | return customerRepository.findByEmail(email)
36 | .orElseThrow(() -> new CustomerException("Customer not found by this email : " + email));
37 |
38 | }
39 |
40 | @Override
41 | public List getAllCustomer() throws CustomerException {
42 |
43 | List customers = customerRepository.findAll();
44 |
45 | if (customers.isEmpty())
46 | throw new CustomerException("no customer found");
47 |
48 | return customers;
49 |
50 | }
51 |
52 | @Override
53 | public List getCustomerByAddress(String address) throws CustomerException {
54 |
55 | return customerRepository.findByAddress(address)
56 | .orElseThrow(() -> new CustomerException("No customer found we that address :" + address));
57 |
58 | }
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT/src/main/java/com/masai/service/CustomerUserDetailsService.java:
--------------------------------------------------------------------------------
1 | package com.masai.service;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Optional;
6 |
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.security.authentication.BadCredentialsException;
9 | import org.springframework.security.core.GrantedAuthority;
10 | import org.springframework.security.core.userdetails.User;
11 | import org.springframework.security.core.userdetails.UserDetails;
12 | import org.springframework.security.core.userdetails.UserDetailsService;
13 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
14 | import org.springframework.stereotype.Service;
15 |
16 | import com.masai.model.Customer;
17 | import com.masai.repository.CustomerRepository;
18 |
19 | /*
20 | * SO HERE WE CREATED OUR OWN UserDetailsService CLASS
21 | * WHICH ARE RESPONSIBLE NFOR Authorized OUR USERS
22 | * BY DEFUALT IT USES InMemoryDeatailsService
23 | * FOR AUTHENTICATION OUR USERS
24 | *
25 | *
26 | */
27 | @Service
28 | public class CustomerUserDetailsService implements UserDetailsService {
29 |
30 | @Autowired
31 | private CustomerRepository customerRepository;
32 |
33 | @Override
34 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
35 |
36 | Optional optional = customerRepository.findByEmail(username);
37 |
38 | if (optional.isPresent()) {
39 |
40 | Customer customer = optional.get();
41 |
42 | /*
43 | * HERE WE DECLARED SOME AUTHORITY THAT BELONGS TO THAT USER LIKE ROLE BASED
44 | * PERMISSIONS, FUNTIONALITY AND SO ON
45 | */
46 | List authorities = new ArrayList<>();
47 |
48 | return new User(customer.getEmail(), customer.getPassword(), authorities);
49 |
50 | } else
51 |
52 | throw new BadCredentialsException("User not found with this email :" + username);
53 |
54 | }
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | #db specific properties
2 | spring.datasource.url=jdbc:mysql://localhost:3306/prac
3 | spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
4 | spring.datasource.username=root
5 | spring.datasource.password=root
6 |
7 | #ORM s/w specific properties
8 | spring.jpa.hibernate.ddl-auto=update
9 | spring.jpa.show-sql=true
--------------------------------------------------------------------------------
/Spring_Security_With_JWT/src/test/java/com/masai/SpringSecurityWithoutJwtApplicationTests.java:
--------------------------------------------------------------------------------
1 | package com.masai;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.springframework.boot.test.context.SpringBootTest;
5 |
6 | @SpringBootTest
7 | class SpringSecurityWithoutJwtApplicationTests {
8 |
9 | @Test
10 | void contextLoads() {
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2/SpringSecurityWithJwt/.gitignore:
--------------------------------------------------------------------------------
1 | HELP.md
2 | target/
3 | !.mvn/wrapper/maven-wrapper.jar
4 | !**/src/main/**/target/
5 | !**/src/test/**/target/
6 |
7 | ### STS ###
8 | .apt_generated
9 | .classpath
10 | .factorypath
11 | .project
12 | .settings
13 | .springBeans
14 | .sts4-cache
15 |
16 | ### IntelliJ IDEA ###
17 | .idea
18 | *.iws
19 | *.iml
20 | *.ipr
21 |
22 | ### NetBeans ###
23 | /nbproject/private/
24 | /nbbuild/
25 | /dist/
26 | /nbdist/
27 | /.nb-gradle/
28 | build/
29 | !**/src/main/**/build/
30 | !**/src/test/**/build/
31 |
32 | ### VS Code ###
33 | .vscode/
34 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2/SpringSecurityWithJwt/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Shubh2-0/Spring_Security/a0d45807af1cd2b3f178a105f9b61b8bfaa7c8b6/Spring_Security_With_JWT2/SpringSecurityWithJwt/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2/SpringSecurityWithJwt/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip
2 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar
3 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2/SpringSecurityWithJwt/src/main/java/com/masai/SpringSecurityWithJwtApplication.java:
--------------------------------------------------------------------------------
1 | package com.masai;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class SpringSecurityWithJwtApplication {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(SpringSecurityWithJwtApplication.class, args);
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2/SpringSecurityWithJwt/src/main/java/com/masai/config/AppConfig.java:
--------------------------------------------------------------------------------
1 | package com.masai.config;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.Configuration;
5 | import org.springframework.http.HttpMethod;
6 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
7 | import org.springframework.security.config.http.SessionCreationPolicy;
8 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
9 | import org.springframework.security.crypto.password.PasswordEncoder;
10 | import org.springframework.security.web.SecurityFilterChain;
11 | import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
12 |
13 | @Configuration
14 | public class AppConfig {
15 |
16 | @Bean
17 | public SecurityFilterChain springSecurityConfiguration(HttpSecurity http) throws Exception {
18 |
19 | http
20 | .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
21 | .and()
22 | .csrf().disable()
23 | .authorizeHttpRequests()
24 | .requestMatchers(HttpMethod.POST, "/customers").permitAll()
25 | .anyRequest().authenticated().and()
26 | .addFilterAfter(new JwtTokenGeneratorFilter(), BasicAuthenticationFilter.class)
27 | .addFilterBefore(new JwtTokenValidatorFilter(), BasicAuthenticationFilter.class)
28 | .formLogin()
29 | .and()
30 | .httpBasic();
31 |
32 | return http.build();
33 |
34 | }
35 |
36 | @Bean
37 | public PasswordEncoder passwordEncoder() {
38 |
39 | return new BCryptPasswordEncoder();
40 |
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2/SpringSecurityWithJwt/src/main/java/com/masai/config/JwtTokenGeneratorFilter.java:
--------------------------------------------------------------------------------
1 | package com.masai.config;
2 |
3 | import java.io.IOException;
4 | import java.util.Collection;
5 | import java.util.Date;
6 | import java.util.HashSet;
7 | import java.util.Set;
8 |
9 | import javax.crypto.SecretKey;
10 |
11 | import org.springframework.security.core.Authentication;
12 | import org.springframework.security.core.GrantedAuthority;
13 | import org.springframework.security.core.context.SecurityContextHolder;
14 | import org.springframework.web.filter.OncePerRequestFilter;
15 |
16 | import io.jsonwebtoken.Jwts;
17 | import io.jsonwebtoken.security.Keys;
18 | import jakarta.servlet.FilterChain;
19 | import jakarta.servlet.ServletException;
20 | import jakarta.servlet.http.HttpServletRequest;
21 | import jakarta.servlet.http.HttpServletResponse;
22 |
23 |
24 | public class JwtTokenGeneratorFilter extends OncePerRequestFilter {
25 |
26 | @Override
27 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
28 | throws ServletException, IOException {
29 |
30 | System.out.println("inside doFilter....");
31 |
32 | Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
33 | if (null != authentication) {
34 |
35 | SecretKey key = Keys.hmacShaKeyFor(SecurityConstants.JWT_KEY.getBytes());
36 |
37 | String jwt = Jwts.builder()
38 | .setIssuer("Ratan")
39 | .setSubject("JWT Token")
40 | .claim("username", authentication.getName())
41 | .claim("authorities", populateAuthorities(authentication.getAuthorities()))
42 | .setIssuedAt(new Date())
43 | .setExpiration(new Date(new Date().getTime()+ 30000000)) // expiration time of 8 hours
44 | .signWith(key).compact();
45 |
46 | response.setHeader(SecurityConstants.JWT_HEADER, jwt);
47 |
48 |
49 |
50 | }
51 |
52 | filterChain.doFilter(request, response);
53 |
54 |
55 |
56 | }
57 |
58 |
59 |
60 |
61 | private String populateAuthorities(Collection extends GrantedAuthority> collection) {
62 |
63 | Set authoritiesSet = new HashSet<>();
64 |
65 | for (GrantedAuthority authority : collection) {
66 | authoritiesSet.add(authority.getAuthority());
67 | }
68 | return String.join(",", authoritiesSet);
69 |
70 |
71 | }
72 |
73 |
74 |
75 |
76 | //this make sure that this filter will execute only for first time when client call the api /login at first time
77 | @Override
78 | protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
79 |
80 | return !request.getServletPath().equals("/signIn");
81 | }
82 |
83 |
84 | }
85 |
86 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2/SpringSecurityWithJwt/src/main/java/com/masai/config/SecurityConstants.java:
--------------------------------------------------------------------------------
1 | package com.masai.config;
2 |
3 | public interface SecurityConstants {
4 |
5 | public static final String JWT_KEY ="secretsfhsfjhdkjngdfjkgfgjdlkfjsdkfjsd";
6 | public static final String JWT_HEADER = "Authorization";
7 |
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2/SpringSecurityWithJwt/src/main/java/com/masai/controller/CustomerController.java:
--------------------------------------------------------------------------------
1 | package com.masai.controller;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.http.HttpStatus;
7 | import org.springframework.http.ResponseEntity;
8 | import org.springframework.security.crypto.password.PasswordEncoder;
9 | import org.springframework.web.bind.annotation.DeleteMapping;
10 | import org.springframework.web.bind.annotation.GetMapping;
11 | import org.springframework.web.bind.annotation.PathVariable;
12 | import org.springframework.web.bind.annotation.PostMapping;
13 | import org.springframework.web.bind.annotation.PutMapping;
14 | import org.springframework.web.bind.annotation.RequestBody;
15 | import org.springframework.web.bind.annotation.RestController;
16 |
17 | import com.masai.model.Customer;
18 | import com.masai.service.CustomerService;
19 |
20 | import jakarta.websocket.server.PathParam;
21 |
22 | @RestController
23 | public class CustomerController {
24 |
25 |
26 |
27 |
28 | @Autowired
29 | private CustomerService customerService;
30 |
31 | @Autowired
32 | private PasswordEncoder passwordEncoder;
33 |
34 |
35 | @GetMapping("/hello")
36 | public String testHandler() {
37 | return "Welcome to Spring Security";
38 | }
39 |
40 | @PostMapping("/customers")
41 | public ResponseEntity saveCustomerHandler(@RequestBody Customer customer){
42 |
43 |
44 | customer.setPassword(passwordEncoder.encode(customer.getPassword()));
45 |
46 | Customer registeredCustomer= customerService.registerCustomer(customer);
47 |
48 | return new ResponseEntity<>(registeredCustomer,HttpStatus.ACCEPTED);
49 |
50 | }
51 |
52 | @GetMapping("/customers/{email}")
53 | public ResponseEntity getCustomerByEmailHandler(@PathVariable("email") String email){
54 |
55 |
56 | Customer customer= customerService.getCustomerDetailsByEmail(email);
57 |
58 | return new ResponseEntity<>(customer,HttpStatus.ACCEPTED);
59 |
60 | }
61 |
62 | @GetMapping("/customers")
63 | public ResponseEntity> getAllCustomerHandler(){
64 |
65 |
66 | List customers= customerService.getAllCustomerDetails();
67 |
68 | return new ResponseEntity<>(customers,HttpStatus.ACCEPTED);
69 |
70 | }
71 |
72 |
73 |
74 | }
75 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2/SpringSecurityWithJwt/src/main/java/com/masai/controller/LoginController.java:
--------------------------------------------------------------------------------
1 | package com.masai.controller;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.http.HttpStatus;
5 | import org.springframework.http.ResponseEntity;
6 | import org.springframework.security.authentication.BadCredentialsException;
7 | import org.springframework.security.core.Authentication;
8 | import org.springframework.web.bind.annotation.GetMapping;
9 | import org.springframework.web.bind.annotation.RestController;
10 |
11 | import com.masai.model.Customer;
12 | import com.masai.repository.CustomerRepository;
13 |
14 | @RestController
15 | public class LoginController {
16 |
17 | @Autowired
18 | private CustomerRepository customerRepository;
19 |
20 | @GetMapping("/signIn")
21 | public ResponseEntity getLoggedInCustomerDetailsHandler(Authentication auth){
22 |
23 |
24 | Customer customer= customerRepository.findByEmail(auth.getName()).orElseThrow(() -> new BadCredentialsException("Invalid Username or password"));
25 |
26 | //to get the token in body, pass HttpServletResponse inside this method parameter
27 | // System.out.println(response.getHeaders(SecurityConstants.JWT_HEADER));
28 |
29 |
30 | return new ResponseEntity<>(customer, HttpStatus.ACCEPTED);
31 |
32 |
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2/SpringSecurityWithJwt/src/main/java/com/masai/exception/CustomerException.java:
--------------------------------------------------------------------------------
1 | package com.masai.exception;
2 |
3 | public class CustomerException extends RuntimeException {
4 |
5 | public CustomerException() {
6 | // TODO Auto-generated constructor stub
7 | }
8 |
9 | public CustomerException(String message) {
10 | super(message);
11 | }
12 |
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2/SpringSecurityWithJwt/src/main/java/com/masai/exception/GlobalExceptionHandler.java:
--------------------------------------------------------------------------------
1 | package com.masai.exception;
2 |
3 | import java.time.LocalDateTime;
4 |
5 | import org.springframework.http.HttpStatus;
6 | import org.springframework.http.ResponseEntity;
7 | import org.springframework.web.bind.annotation.ControllerAdvice;
8 | import org.springframework.web.bind.annotation.ExceptionHandler;
9 | import org.springframework.web.context.request.WebRequest;
10 |
11 | @ControllerAdvice
12 | public class GlobalExceptionHandler {
13 |
14 |
15 |
16 |
17 |
18 | @ExceptionHandler(CustomerException.class)
19 | public ResponseEntity customerExceptionHandler(CustomerException ce, WebRequest req){
20 |
21 |
22 | MyErrorDetails err= new MyErrorDetails();
23 | err.setTimestamp(LocalDateTime.now());
24 | err.setMessage(ce.getMessage());
25 | err.setDetails(req.getDescription(false));
26 |
27 | return new ResponseEntity(err, HttpStatus.BAD_REQUEST);
28 |
29 | }
30 |
31 |
32 |
33 | @ExceptionHandler(Exception.class)
34 | public ResponseEntity otherExceptionHandler(Exception se, WebRequest req){
35 |
36 |
37 | MyErrorDetails err= new MyErrorDetails();
38 | err.setTimestamp(LocalDateTime.now());
39 | err.setMessage(se.getMessage());
40 | err.setDetails(req.getDescription(false));
41 |
42 | return new ResponseEntity(err, HttpStatus.INTERNAL_SERVER_ERROR);
43 |
44 | }
45 |
46 |
47 |
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2/SpringSecurityWithJwt/src/main/java/com/masai/exception/MyErrorDetails.java:
--------------------------------------------------------------------------------
1 | package com.masai.exception;
2 |
3 | import java.time.LocalDateTime;
4 |
5 | public class MyErrorDetails {
6 |
7 | private LocalDateTime timestamp;
8 | private String message;
9 | private String details;
10 |
11 |
12 | public MyErrorDetails() {
13 | // TODO Auto-generated constructor stub
14 | }
15 |
16 |
17 | public MyErrorDetails(LocalDateTime timestamp, String message, String details) {
18 | super();
19 | this.timestamp = timestamp;
20 | this.message = message;
21 | this.details = details;
22 | }
23 |
24 |
25 | public LocalDateTime getTimestamp() {
26 | return timestamp;
27 | }
28 |
29 |
30 | public void setTimestamp(LocalDateTime timestamp) {
31 | this.timestamp = timestamp;
32 | }
33 |
34 |
35 | public String getMessage() {
36 | return message;
37 | }
38 |
39 |
40 | public void setMessage(String message) {
41 | this.message = message;
42 | }
43 |
44 |
45 | public String getDetails() {
46 | return details;
47 | }
48 |
49 |
50 | public void setDetails(String details) {
51 | this.details = details;
52 | }
53 |
54 |
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2/SpringSecurityWithJwt/src/main/java/com/masai/model/Customer.java:
--------------------------------------------------------------------------------
1 | package com.masai.model;
2 |
3 | import com.fasterxml.jackson.annotation.JsonProperty;
4 |
5 | import jakarta.persistence.Column;
6 | import jakarta.persistence.Entity;
7 | import jakarta.persistence.GeneratedValue;
8 | import jakarta.persistence.GenerationType;
9 | import jakarta.persistence.Id;
10 | import jakarta.persistence.UniqueConstraint;
11 | import lombok.Data;
12 |
13 | @Entity
14 | @Data
15 | public class Customer {
16 |
17 | @Id
18 | @GeneratedValue(strategy = GenerationType.AUTO)
19 | private Integer custId;
20 | private String name;
21 |
22 | @Column(unique = true)
23 | private String email;
24 | @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
25 | private String password;
26 | private String address;
27 |
28 |
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2/SpringSecurityWithJwt/src/main/java/com/masai/repository/CustomerRepository.java:
--------------------------------------------------------------------------------
1 | package com.masai.repository;
2 |
3 | import java.util.Optional;
4 |
5 | import org.springframework.data.jpa.repository.JpaRepository;
6 |
7 | import com.masai.model.Customer;
8 |
9 | public interface CustomerRepository extends JpaRepository{
10 |
11 |
12 | public Optional findByEmail(String email);
13 | }
14 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2/SpringSecurityWithJwt/src/main/java/com/masai/service/CustomerService.java:
--------------------------------------------------------------------------------
1 | package com.masai.service;
2 | import java.util.List;
3 |
4 | import com.masai.exception.CustomerException;
5 | import com.masai.model.Customer;
6 |
7 | public interface CustomerService {
8 |
9 | public Customer registerCustomer(Customer customer);
10 |
11 | public Customer getCustomerDetailsByEmail(String email)throws CustomerException;
12 |
13 | public List getAllCustomerDetails()throws CustomerException;
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2/SpringSecurityWithJwt/src/main/java/com/masai/service/CustomerServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.masai.service;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.stereotype.Service;
7 |
8 | import com.masai.exception.CustomerException;
9 | import com.masai.model.Customer;
10 | import com.masai.repository.CustomerRepository;
11 |
12 | @Service
13 | public class CustomerServiceImpl implements CustomerService{
14 |
15 | @Autowired
16 | private CustomerRepository customerRepository;
17 |
18 | @Override
19 | public Customer registerCustomer(Customer customer) throws CustomerException {
20 |
21 | return customerRepository.save(customer);
22 |
23 |
24 | }
25 |
26 | @Override
27 | public Customer getCustomerDetailsByEmail(String email)throws CustomerException {
28 |
29 | return customerRepository.findByEmail(email).orElseThrow(() -> new CustomerException("Customer Not found with Email: "+email));
30 | }
31 |
32 | @Override
33 | public List getAllCustomerDetails()throws CustomerException {
34 |
35 | List customers= customerRepository.findAll();
36 |
37 | if(customers.isEmpty())
38 | throw new CustomerException("No Customer find");
39 |
40 | return customers;
41 |
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2/SpringSecurityWithJwt/src/main/java/com/masai/service/CustomerUserDetailsService.java:
--------------------------------------------------------------------------------
1 | package com.masai.service;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Optional;
6 |
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.security.authentication.BadCredentialsException;
9 | import org.springframework.security.core.GrantedAuthority;
10 | import org.springframework.security.core.userdetails.User;
11 | import org.springframework.security.core.userdetails.UserDetails;
12 | import org.springframework.security.core.userdetails.UserDetailsService;
13 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
14 | import org.springframework.stereotype.Service;
15 |
16 | import com.masai.model.Customer;
17 | import com.masai.repository.CustomerRepository;
18 |
19 | @Service
20 | public class CustomerUserDetailsService implements UserDetailsService{
21 |
22 | @Autowired
23 | private CustomerRepository customerRepository;
24 |
25 |
26 | @Override
27 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
28 |
29 |
30 | Optional opt= customerRepository.findByEmail(username);
31 |
32 | if(opt.isPresent()) {
33 |
34 | Customer customer= opt.get();
35 |
36 | List authorities= new ArrayList<>();
37 | //authorities.add(new SimpleGrantedAuthority(customer.getRole()));
38 |
39 |
40 | return new User(customer.getEmail(), customer.getPassword(), authorities);
41 |
42 |
43 |
44 | }else
45 | throw new BadCredentialsException("User Details not found with this username: "+username);
46 |
47 |
48 |
49 |
50 |
51 | }
52 |
53 | }
54 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2/SpringSecurityWithJwt/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 |
2 | #db specific properties
3 | spring.datasource.url=jdbc:mysql://localhost:3306/masaidb
4 | spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
5 | spring.datasource.username=root
6 | spring.datasource.password=root
7 |
8 | #ORM s/w specific properties
9 | spring.jpa.hibernate.ddl-auto=update
10 | spring.jpa.show-sql=true
11 |
12 | #spring.security.user.name=ratan
13 | #spring.security.user.password=123
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2/SpringSecurityWithJwt/src/test/java/com/masai/SpringSecurityWithJwtApplicationTests.java:
--------------------------------------------------------------------------------
1 | package com.masai;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.springframework.boot.test.context.SpringBootTest;
5 |
6 | @SpringBootTest
7 | class SpringSecurityWithJwtApplicationTests {
8 |
9 | @Test
10 | void contextLoads() {
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2_And_Role/.gitignore:
--------------------------------------------------------------------------------
1 | HELP.md
2 | target/
3 | !.mvn/wrapper/maven-wrapper.jar
4 | !**/src/main/**/target/
5 | !**/src/test/**/target/
6 |
7 | ### STS ###
8 | .apt_generated
9 | .classpath
10 | .factorypath
11 | .project
12 | .settings
13 | .springBeans
14 | .sts4-cache
15 |
16 | ### IntelliJ IDEA ###
17 | .idea
18 | *.iws
19 | *.iml
20 | *.ipr
21 |
22 | ### NetBeans ###
23 | /nbproject/private/
24 | /nbbuild/
25 | /dist/
26 | /nbdist/
27 | /.nb-gradle/
28 | build/
29 | !**/src/main/**/build/
30 | !**/src/test/**/build/
31 |
32 | ### VS Code ###
33 | .vscode/
34 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2_And_Role/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Shubh2-0/Spring_Security/a0d45807af1cd2b3f178a105f9b61b8bfaa7c8b6/Spring_Security_With_JWT2_And_Role/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2_And_Role/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.3/apache-maven-3.9.3-bin.zip
2 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar
3 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2_And_Role/src/main/java/com/masai/SpringSecurityWithoutJwtApplication.java:
--------------------------------------------------------------------------------
1 | package com.masai;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class SpringSecurityWithoutJwtApplication {
8 |
9 | /*
10 | * MAIN INTERFACE WHERE OUR APPLICATION IS STARTED THIS CLASS BY DEFAULT CREATED
11 | * BY SPRING BOOT
12 | */
13 |
14 | public static void main(String[] args) {
15 | SpringApplication.run(SpringSecurityWithoutJwtApplication.class, args);
16 | }
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2_And_Role/src/main/java/com/masai/config/AppConfig.java:
--------------------------------------------------------------------------------
1 | package com.masai.config;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.Configuration;
5 | import org.springframework.http.HttpMethod;
6 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
7 | import org.springframework.security.config.http.SessionCreationPolicy;
8 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
9 | import org.springframework.security.crypto.password.PasswordEncoder;
10 | import org.springframework.security.web.SecurityFilterChain;
11 | import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
12 |
13 | @Configuration
14 | public class AppConfig {
15 |
16 | @Bean
17 | public SecurityFilterChain springSecurityConfiguration(HttpSecurity http) throws Exception {
18 |
19 | http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().csrf().disable()
20 | .authorizeHttpRequests().requestMatchers(HttpMethod.POST, "/customers").permitAll()
21 | .requestMatchers(HttpMethod.GET, "/customers").hasRole("ADMIN")
22 | .requestMatchers(HttpMethod.GET, "/customers/**").hasAnyRole("ADMIN", "USER").anyRequest()
23 | .authenticated().and().addFilterAfter(new JwtTokenGeneratorFilter(), BasicAuthenticationFilter.class)
24 | .addFilterBefore(new JwtTokenValidatorFilter(), BasicAuthenticationFilter.class).formLogin().and()
25 | .httpBasic();
26 |
27 | return http.build();
28 |
29 | }
30 |
31 | @Bean
32 | public PasswordEncoder passwordEncoder() {
33 |
34 | return new BCryptPasswordEncoder();
35 |
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2_And_Role/src/main/java/com/masai/config/JwtTokenGeneratorFilter.java:
--------------------------------------------------------------------------------
1 | package com.masai.config;
2 |
3 | import java.io.IOException;
4 | import java.util.Collection;
5 | import java.util.Date;
6 |
7 | import javax.crypto.SecretKey;
8 |
9 | import org.springframework.security.core.Authentication;
10 | import org.springframework.security.core.GrantedAuthority;
11 | import org.springframework.security.core.context.SecurityContextHolder;
12 | import org.springframework.web.filter.OncePerRequestFilter;
13 |
14 | import io.jsonwebtoken.Jwts;
15 | import io.jsonwebtoken.security.Keys;
16 | import jakarta.servlet.FilterChain;
17 | import jakarta.servlet.ServletException;
18 | import jakarta.servlet.http.HttpServletRequest;
19 | import jakarta.servlet.http.HttpServletResponse;
20 |
21 | public class JwtTokenGeneratorFilter extends OncePerRequestFilter {
22 |
23 | @Override
24 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
25 | throws ServletException, IOException {
26 |
27 | System.out.println("inside doFilter....");
28 |
29 | Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
30 | if (null != authentication) {
31 |
32 | System.out.println("authenticationnnn " + authentication);
33 |
34 | SecretKey key = Keys.hmacShaKeyFor(SecurityConstants.JWT_KEY.getBytes());
35 |
36 | String jwt = Jwts.builder().setIssuer("Ratan").setSubject("JWT Token")
37 | .claim("username", authentication.getName()).claim("role", getRole(authentication.getAuthorities()))
38 | .setIssuedAt(new Date()).setExpiration(new Date(new Date().getTime() + 30000000)) // expiration time
39 | // of 8 hours
40 | .signWith(key).compact();
41 |
42 | response.setHeader(SecurityConstants.JWT_HEADER, jwt);
43 |
44 | }
45 |
46 | filterChain.doFilter(request, response);
47 |
48 | }
49 |
50 | private String getRole(Collection extends GrantedAuthority> collection) {
51 |
52 | String role = "";
53 | for (GrantedAuthority ga : collection) {
54 | role = ga.getAuthority();
55 | }
56 |
57 | return role;
58 | }
59 |
60 | //this make sure that this filter will execute only for first time when client call the api /login at first time
61 | @Override
62 | protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
63 |
64 | return !request.getServletPath().equals("/signIn");
65 | }
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2_And_Role/src/main/java/com/masai/config/JwtTokenValidatorFilter.java:
--------------------------------------------------------------------------------
1 | package com.masai.config;
2 |
3 | import java.io.IOException;
4 | import java.util.ArrayList;
5 | import java.util.List;
6 |
7 | import javax.crypto.SecretKey;
8 |
9 | import org.springframework.security.authentication.BadCredentialsException;
10 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
11 | import org.springframework.security.core.Authentication;
12 | import org.springframework.security.core.GrantedAuthority;
13 | import org.springframework.security.core.authority.SimpleGrantedAuthority;
14 | import org.springframework.security.core.context.SecurityContextHolder;
15 | import org.springframework.web.filter.OncePerRequestFilter;
16 |
17 | import io.jsonwebtoken.Claims;
18 | import io.jsonwebtoken.Jwts;
19 | import io.jsonwebtoken.security.Keys;
20 | import jakarta.servlet.FilterChain;
21 | import jakarta.servlet.ServletException;
22 | import jakarta.servlet.http.HttpServletRequest;
23 | import jakarta.servlet.http.HttpServletResponse;
24 |
25 | public class JwtTokenValidatorFilter extends OncePerRequestFilter {
26 |
27 | @Override
28 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
29 | throws ServletException, IOException {
30 |
31 | String jwt = request.getHeader(SecurityConstants.JWT_HEADER);
32 |
33 | if (jwt != null) {
34 |
35 | try {
36 |
37 | // extracting the word Bearer
38 | jwt = jwt.substring(7);
39 |
40 | SecretKey key = Keys.hmacShaKeyFor(SecurityConstants.JWT_KEY.getBytes());
41 |
42 | Claims claims = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(jwt).getBody();
43 |
44 | String username = String.valueOf(claims.get("username"));
45 |
46 | String role = (String) claims.get("role");
47 |
48 | List authorities = new ArrayList<>();
49 | authorities.add(new SimpleGrantedAuthority(role));
50 |
51 | Authentication auth = new UsernamePasswordAuthenticationToken(username, null, authorities);
52 |
53 | SecurityContextHolder.getContext().setAuthentication(auth);
54 |
55 | } catch (Exception e) {
56 | throw new BadCredentialsException("Invalid Token received..");
57 | }
58 |
59 | }
60 |
61 | filterChain.doFilter(request, response);
62 |
63 | }
64 |
65 | // this time this validation filter has to be executed for all the apis except
66 | // the /login api
67 |
68 | @Override
69 | protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
70 |
71 | return request.getServletPath().equals("/signIn");
72 | }
73 |
74 | }
75 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2_And_Role/src/main/java/com/masai/config/SecurityConstants.java:
--------------------------------------------------------------------------------
1 | package com.masai.config;
2 |
3 | public interface SecurityConstants {
4 |
5 | public static final String JWT_KEY ="ddsmdskjsmdskkljnssmscsccdcdd";
6 | public static final String JWT_HEADER="Authorization";
7 |
8 | }
9 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2_And_Role/src/main/java/com/masai/controller/CustomerController.java:
--------------------------------------------------------------------------------
1 | package com.masai.controller;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.http.HttpStatus;
7 | import org.springframework.http.ResponseEntity;
8 | import org.springframework.security.crypto.password.PasswordEncoder;
9 | import org.springframework.web.bind.annotation.GetMapping;
10 | import org.springframework.web.bind.annotation.PathVariable;
11 | import org.springframework.web.bind.annotation.PostMapping;
12 | import org.springframework.web.bind.annotation.RequestBody;
13 | import org.springframework.web.bind.annotation.RestController;
14 |
15 | import com.masai.exception.CustomerException;
16 | import com.masai.model.Customer;
17 | import com.masai.service.CustomerService;
18 |
19 | /*
20 | OUR RESTCONTROLLER WHERE WE CREATE
21 | ENDPOINTS(APIs)
22 | */
23 |
24 | @RestController
25 | public class CustomerController {
26 |
27 | @Autowired
28 | private CustomerService customerService;
29 |
30 | /*
31 | * THIS OBJECT IS RESPONSIBLE FOR CONVERTED THE USER PASSWORD INTO base64
32 | * ENCODED VERSION
33 | */
34 | @Autowired
35 | private PasswordEncoder passwordEncoder;
36 |
37 | @GetMapping("/learn")
38 | public String testHandler() {
39 |
40 | return "LEARNING SPRING SECURITY";
41 |
42 | }
43 |
44 | @PostMapping("/customers")
45 | public ResponseEntity addCustomerHandler(@RequestBody Customer customer) throws CustomerException {
46 |
47 | customer.setRole("ROLE_" + customer.getRole().toUpperCase());
48 |
49 | // HERE WE CHANGE THE NORMAL USER PASSWORD INTO base64 encoded VERSION
50 | customer.setPassword(passwordEncoder.encode(customer.getPassword()));
51 |
52 | Customer registorCustomer = customerService.addCustomer(customer);
53 |
54 | return new ResponseEntity(registorCustomer, HttpStatus.ACCEPTED);
55 |
56 | }
57 |
58 | @GetMapping("/customers/{email}")
59 | public ResponseEntity getCustomerbyEmailHandler(@PathVariable("email") String email)
60 | throws CustomerException {
61 |
62 | return new ResponseEntity(customerService.getCustomerByEmail(email), HttpStatus.ACCEPTED);
63 |
64 | }
65 |
66 | @GetMapping("/customers/all")
67 | public ResponseEntity> getAllCustomerHandler() throws CustomerException {
68 |
69 | return new ResponseEntity>(customerService.getAllCustomer(), HttpStatus.ACCEPTED);
70 |
71 | }
72 |
73 | @GetMapping("/customers/address/{address}")
74 | public ResponseEntity> getAllCustomerByAddressHandler(@PathVariable("address") String address)
75 | throws CustomerException {
76 |
77 | return new ResponseEntity>(customerService.getCustomerByAddress(address), HttpStatus.ACCEPTED);
78 | }
79 |
80 | }
81 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2_And_Role/src/main/java/com/masai/controller/CustomerLoginController.java:
--------------------------------------------------------------------------------
1 | package com.masai.controller;
2 |
3 |
4 | import org.springframework.beans.factory.annotation.Autowired;
5 | import org.springframework.http.HttpStatus;
6 | import org.springframework.http.ResponseEntity;
7 | import org.springframework.security.authentication.BadCredentialsException;
8 | import org.springframework.security.core.Authentication;
9 | import org.springframework.web.bind.annotation.GetMapping;
10 | import org.springframework.web.bind.annotation.RestController;
11 |
12 | import com.masai.model.Customer;
13 | import com.masai.repository.CustomerRepository;
14 |
15 | @RestController
16 | public class CustomerLoginController {
17 |
18 | @Autowired
19 | private CustomerRepository customerRepository;
20 |
21 |
22 | /*
23 | * HERE WE CREATED ONE ENDPOINT FOR signIn THE USER
24 | * IT WILL TAKE Authentication object
25 | * IN Authentication object WE HAVE THE USERNAME AND PASSWORD OF THE USER
26 | * IN WHICH WE CAN FIND THE USER BY THIER USERNAME
27 | */
28 | @GetMapping("/signIn")
29 | public ResponseEntity getLoggedInCustomerHandler(Authentication auth){
30 |
31 | System.out.println("AUTHENTICATION OBJECT :"+ auth);
32 |
33 | /* IN Authentication object WE HAVE SOME METHOD WHERE WE CAN ACCESS THE USER INFORMATION
34 | * ONE OF THEM ARE getName() WHICH BASICALLY return THE USER username
35 | *
36 | */
37 | Customer customer = customerRepository.findByEmail(auth.getName()).orElseThrow((() -> new BadCredentialsException("invalid email")));
38 |
39 |
40 | return new ResponseEntity(customer,HttpStatus.ACCEPTED);
41 |
42 | }
43 |
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2_And_Role/src/main/java/com/masai/exception/CustomError.java:
--------------------------------------------------------------------------------
1 | package com.masai.exception;
2 |
3 | import java.time.LocalDateTime;
4 |
5 | import lombok.AllArgsConstructor;
6 | import lombok.Data;
7 | import lombok.NoArgsConstructor;
8 |
9 | @Data
10 | @NoArgsConstructor
11 | @AllArgsConstructor
12 |
13 | /*
14 | * HERE WE CREATED OUR OWN CUSTOME EXCEPTION OR ERROR IN SIMPLE BODY OF OUR
15 | * ERROR
16 | */
17 | public class CustomError {
18 |
19 | private LocalDateTime time;
20 | private String message;
21 | private String details;
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2_And_Role/src/main/java/com/masai/exception/CustomerException.java:
--------------------------------------------------------------------------------
1 | package com.masai.exception;
2 |
3 | public class CustomerException extends Exception {
4 |
5 | public CustomerException(String m) {
6 |
7 | super(m);
8 | }
9 |
10 | }
11 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2_And_Role/src/main/java/com/masai/exception/GlobalExceptionHandler.java:
--------------------------------------------------------------------------------
1 | package com.masai.exception;
2 |
3 | import java.time.LocalDateTime;
4 |
5 | import org.springframework.http.HttpStatus;
6 | import org.springframework.http.ResponseEntity;
7 | import org.springframework.web.bind.annotation.ControllerAdvice;
8 | import org.springframework.web.bind.annotation.ExceptionHandler;
9 | import org.springframework.web.context.request.WebRequest;
10 |
11 | @ControllerAdvice
12 | public class GlobalExceptionHandler {
13 |
14 | /*
15 | * HERE WE CREATE OUR OWN CUSTOME ERROR SO WHEN ANY EEXCEPTION ACCUR SO THAT
16 | * EXCEPTION HANDLER HANDLE THAT SITUATION
17 | *
18 | */
19 | @ExceptionHandler(CustomerException.class)
20 | public ResponseEntity customerExceptionHandler(CustomerException e, WebRequest req) {
21 |
22 | CustomError error = new CustomError();
23 | error.setTime(LocalDateTime.now());
24 | error.setMessage(e.getMessage());
25 | error.setDetails(req.getDescription(false));
26 |
27 | return new ResponseEntity(error, HttpStatus.BAD_REQUEST);
28 |
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2_And_Role/src/main/java/com/masai/model/Customer.java:
--------------------------------------------------------------------------------
1 | package com.masai.model;
2 |
3 | import com.fasterxml.jackson.annotation.JsonProperty;
4 |
5 | import jakarta.annotation.Generated;
6 | import jakarta.persistence.Column;
7 | import jakarta.persistence.Entity;
8 | import jakarta.persistence.GeneratedValue;
9 | import jakarta.persistence.GenerationType;
10 | import jakarta.persistence.Id;
11 | import lombok.AllArgsConstructor;
12 | import lombok.Data;
13 | import lombok.NoArgsConstructor;
14 |
15 | @Entity
16 | @Data
17 | @NoArgsConstructor
18 | @AllArgsConstructor
19 | public class Customer {
20 |
21 | @Id
22 | @GeneratedValue(strategy = GenerationType.AUTO)
23 | private Integer Id;
24 |
25 | private String name;
26 |
27 | @Column(unique = true)
28 | private String email;
29 |
30 | /*
31 | * AT THE TIME OF FETCHING ANY USER WE CAN'T SEE THIER PASSWORD BECUASE OF THIS
32 | * PROPERTY
33 | */
34 | @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
35 | private String password;
36 |
37 | private String address;
38 |
39 | private String role;
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2_And_Role/src/main/java/com/masai/repository/CustomerRepository.java:
--------------------------------------------------------------------------------
1 | package com.masai.repository;
2 |
3 | import java.util.List;
4 | import java.util.Optional;
5 |
6 | import org.springframework.data.jpa.repository.JpaRepository;
7 |
8 | import com.masai.model.Customer;
9 |
10 | public interface CustomerRepository extends JpaRepository {
11 |
12 | /*
13 | * HERE WE CREATE A METHOD WHERE WE CAN FIND THE USER BY THIER EMAIL ADDRESS AND
14 | * ALSO HERE WE USE Optional CLAS FOR ACCHIEVING THE FUNCTIONAL WAY
15 | */
16 | public Optional findByEmail(String email);
17 |
18 | /*
19 | * HERE WE CREATE A METHOD WHERE WE CAN FIND THE USER BY THIER ADDRESS ALSO
20 | */
21 | public Optional> findByAddress(String address);
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2_And_Role/src/main/java/com/masai/service/CustomerService.java:
--------------------------------------------------------------------------------
1 | package com.masai.service;
2 |
3 | import java.util.List;
4 |
5 | import com.masai.exception.CustomerException;
6 | import com.masai.model.Customer;
7 |
8 | public interface CustomerService {
9 |
10 | Customer addCustomer(Customer customer) throws CustomerException;
11 |
12 | Customer getCustomerByEmail(String email) throws CustomerException;
13 |
14 | List getAllCustomer() throws CustomerException;
15 |
16 | List getCustomerByAddress(String address) throws CustomerException;
17 | }
18 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2_And_Role/src/main/java/com/masai/service/CustomerServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.masai.service;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.stereotype.Service;
7 |
8 | import com.masai.exception.CustomerException;
9 | import com.masai.model.Customer;
10 | import com.masai.repository.CustomerRepository;
11 |
12 | @Service
13 | public class CustomerServiceImpl implements CustomerService {
14 |
15 | @Autowired
16 | private CustomerRepository customerRepository;
17 |
18 | @Override
19 | public Customer addCustomer(Customer customer) throws CustomerException {
20 |
21 | return customerRepository.save(customer);
22 |
23 | }
24 |
25 | @Override
26 | public Customer getCustomerByEmail(String email) throws CustomerException {
27 |
28 | /*
29 | * HERE WE USE FUNCTIONAL WHY TO RETURN THE CUSTOMER OBJECT IT'S POSSIBLE BY THE
30 | * HELP OF Optional CLASS IF THE OPTIONAL IS NOT EMPTY THAN IT RETURN THE
31 | * CUSTOMER OBJECT OTHER WISE IT THROW THE CustomerException IT ISE VERY SIMPLE
32 | * AND EASY
33 | *
34 | */
35 | return customerRepository.findByEmail(email)
36 | .orElseThrow(() -> new CustomerException("Customer not found by this email : " + email));
37 |
38 | }
39 |
40 | @Override
41 | public List getAllCustomer() throws CustomerException {
42 |
43 | List customers = customerRepository.findAll();
44 |
45 | if (customers.isEmpty())
46 | throw new CustomerException("no customer found");
47 |
48 | return customers;
49 |
50 | }
51 |
52 | @Override
53 | public List getCustomerByAddress(String address) throws CustomerException {
54 |
55 | return customerRepository.findByAddress(address)
56 | .orElseThrow(() -> new CustomerException("No customer found we that address :" + address));
57 |
58 | }
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2_And_Role/src/main/java/com/masai/service/CustomerUserDetailsService.java:
--------------------------------------------------------------------------------
1 | package com.masai.service;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Optional;
6 |
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.security.authentication.BadCredentialsException;
9 | import org.springframework.security.core.GrantedAuthority;
10 | import org.springframework.security.core.authority.SimpleGrantedAuthority;
11 | import org.springframework.security.core.userdetails.User;
12 | import org.springframework.security.core.userdetails.UserDetails;
13 | import org.springframework.security.core.userdetails.UserDetailsService;
14 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
15 | import org.springframework.stereotype.Service;
16 |
17 | import com.masai.model.Customer;
18 | import com.masai.repository.CustomerRepository;
19 |
20 | /*
21 | * SO HERE WE CREATED OUR OWN UserDetailsService CLASS
22 | * WHICH ARE RESPONSIBLE NFOR Authorized OUR USERS
23 | * BY DEFUALT IT USES InMemoryDeatailsService
24 | * FOR AUTHENTICATION OUR USERS
25 | *
26 | *
27 | */
28 | @Service
29 | public class CustomerUserDetailsService implements UserDetailsService {
30 |
31 | @Autowired
32 | private CustomerRepository customerRepository;
33 |
34 | @Override
35 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
36 |
37 | Optional optional = customerRepository.findByEmail(username);
38 |
39 | if (optional.isPresent()) {
40 |
41 | Customer customer = optional.get();
42 |
43 | /*
44 | * HERE WE DECLARED SOME AUTHORITY THAT BELONGS TO THAT USER LIKE ROLE BASED
45 | * PERMISSIONS, FUNTIONALITY AND SO ON
46 | */
47 | List authorities = new ArrayList<>();
48 |
49 | SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(customer.getRole());
50 |
51 | authorities.add(simpleGrantedAuthority);
52 |
53 | return new User(customer.getEmail(), customer.getPassword(), authorities);
54 |
55 | } else
56 |
57 | throw new BadCredentialsException("User not found with this email :" + username);
58 |
59 | }
60 |
61 | }
62 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2_And_Role/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | #db specific properties
2 | spring.datasource.url=jdbc:mysql://localhost:3306/prac
3 | spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
4 | spring.datasource.username=root
5 | spring.datasource.password=root
6 |
7 | #ORM s/w specific properties
8 | spring.jpa.hibernate.ddl-auto=update
9 | spring.jpa.show-sql=true
--------------------------------------------------------------------------------
/Spring_Security_With_JWT2_And_Role/src/test/java/com/masai/SpringSecurityWithoutJwtApplicationTests.java:
--------------------------------------------------------------------------------
1 | package com.masai;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.springframework.boot.test.context.SpringBootTest;
5 |
6 | @SpringBootTest
7 | class SpringSecurityWithoutJwtApplicationTests {
8 |
9 | @Test
10 | void contextLoads() {
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT_Cors/SpringSecurityWithJwtCors/.gitignore:
--------------------------------------------------------------------------------
1 | HELP.md
2 | target/
3 | !.mvn/wrapper/maven-wrapper.jar
4 | !**/src/main/**/target/
5 | !**/src/test/**/target/
6 |
7 | ### STS ###
8 | .apt_generated
9 | .classpath
10 | .factorypath
11 | .project
12 | .settings
13 | .springBeans
14 | .sts4-cache
15 |
16 | ### IntelliJ IDEA ###
17 | .idea
18 | *.iws
19 | *.iml
20 | *.ipr
21 |
22 | ### NetBeans ###
23 | /nbproject/private/
24 | /nbbuild/
25 | /dist/
26 | /nbdist/
27 | /.nb-gradle/
28 | build/
29 | !**/src/main/**/build/
30 | !**/src/test/**/build/
31 |
32 | ### VS Code ###
33 | .vscode/
34 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT_Cors/SpringSecurityWithJwtCors/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Shubh2-0/Spring_Security/a0d45807af1cd2b3f178a105f9b61b8bfaa7c8b6/Spring_Security_With_JWT_Cors/SpringSecurityWithJwtCors/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/Spring_Security_With_JWT_Cors/SpringSecurityWithJwtCors/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip
2 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar
3 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT_Cors/SpringSecurityWithJwtCors/src/main/java/com/masai/SpringSecurityWithJwtCorsApplication.java:
--------------------------------------------------------------------------------
1 | package com.masai;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class SpringSecurityWithJwtCorsApplication {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(SpringSecurityWithJwtCorsApplication.class, args);
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT_Cors/SpringSecurityWithJwtCors/src/main/java/com/masai/config/AppConfig.java:
--------------------------------------------------------------------------------
1 | package com.masai.config;
2 |
3 | import java.util.Arrays;
4 | import java.util.Collections;
5 |
6 | import org.springframework.context.annotation.Bean;
7 | import org.springframework.context.annotation.Configuration;
8 | import org.springframework.http.HttpMethod;
9 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
10 | import org.springframework.security.config.http.SessionCreationPolicy;
11 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
12 | import org.springframework.security.crypto.password.PasswordEncoder;
13 | import org.springframework.security.web.SecurityFilterChain;
14 | import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
15 | import org.springframework.web.cors.CorsConfiguration;
16 | import org.springframework.web.cors.CorsConfigurationSource;
17 |
18 | import jakarta.servlet.http.HttpServletRequest;
19 |
20 | @Configuration
21 | public class AppConfig {
22 |
23 | @Bean
24 | public SecurityFilterChain springSecurityConfiguration(HttpSecurity http) throws Exception {
25 |
26 | http
27 | .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
28 | .and()
29 | .csrf().disable()
30 | .cors().configurationSource( new CorsConfigurationSource() {
31 |
32 | @Override
33 | public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
34 |
35 |
36 |
37 | CorsConfiguration cfg = new CorsConfiguration();
38 |
39 | cfg.setAllowedOrigins(Collections.singletonList("*"));
40 | //cfg.setAllowedOrigins(Arrays.asList("http://localhost:4200", "http://localhost:4500"));
41 | //cfg.setAllowedMethods(Arrays.asList("GET", "POST","DELETE","PUT"));
42 | cfg.setAllowedMethods(Collections.singletonList("*"));
43 | cfg.setAllowCredentials(true);
44 | cfg.setAllowedHeaders(Collections.singletonList("*"));
45 | cfg.setExposedHeaders(Arrays.asList("Authorization"));
46 | cfg.setMaxAge(3600L);
47 | return cfg;
48 |
49 |
50 |
51 | }
52 | })
53 | .and()
54 | .addFilterAfter(new JwtTokenGeneratorFilter(), BasicAuthenticationFilter.class)
55 | .addFilterBefore(new JwtTokenValidatorFilter(), BasicAuthenticationFilter.class)
56 | .authorizeHttpRequests()
57 | .requestMatchers(HttpMethod.POST, "/customers")
58 | .permitAll().anyRequest()
59 | .authenticated()
60 | .and()
61 | .formLogin()
62 | .and()
63 | .httpBasic();
64 |
65 | return http.build();
66 |
67 | }
68 |
69 | @Bean
70 | public PasswordEncoder passwordEncoder() {
71 |
72 | return new BCryptPasswordEncoder();
73 |
74 | }
75 |
76 | }
77 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT_Cors/SpringSecurityWithJwtCors/src/main/java/com/masai/config/SecurityConstants.java:
--------------------------------------------------------------------------------
1 | package com.masai.config;
2 |
3 | public interface SecurityConstants {
4 |
5 | public static final String JWT_KEY ="secretsfhsfjhdkjngdfjkgfgjdlkfjsdkfjsd";
6 | public static final String JWT_HEADER = "Authorization";
7 |
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT_Cors/SpringSecurityWithJwtCors/src/main/java/com/masai/controller/CustomerController.java:
--------------------------------------------------------------------------------
1 | package com.masai.controller;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.http.HttpStatus;
7 | import org.springframework.http.ResponseEntity;
8 | import org.springframework.security.crypto.password.PasswordEncoder;
9 | import org.springframework.web.bind.annotation.DeleteMapping;
10 | import org.springframework.web.bind.annotation.GetMapping;
11 | import org.springframework.web.bind.annotation.PathVariable;
12 | import org.springframework.web.bind.annotation.PostMapping;
13 | import org.springframework.web.bind.annotation.PutMapping;
14 | import org.springframework.web.bind.annotation.RequestBody;
15 | import org.springframework.web.bind.annotation.RestController;
16 |
17 | import com.masai.model.Customer;
18 | import com.masai.service.CustomerService;
19 |
20 | import jakarta.websocket.server.PathParam;
21 |
22 | @RestController
23 | public class CustomerController {
24 |
25 |
26 |
27 |
28 | @Autowired
29 | private CustomerService customerService;
30 |
31 | @Autowired
32 | private PasswordEncoder passwordEncoder;
33 |
34 |
35 | @GetMapping("/hello")
36 | public String testHandler() {
37 | return "Welcome to Spring Security";
38 | }
39 |
40 | @PostMapping("/customers")
41 | public ResponseEntity saveCustomerHandler(@RequestBody Customer customer){
42 |
43 | customer.setPassword(passwordEncoder.encode(customer.getPassword()));
44 |
45 | Customer registeredCustomer= customerService.registerCustomer(customer);
46 |
47 | return new ResponseEntity<>(registeredCustomer,HttpStatus.ACCEPTED);
48 |
49 | }
50 |
51 | @GetMapping("/customers/{email}")
52 | public ResponseEntity getCustomerByEmailHandler(@PathVariable("email") String email){
53 |
54 |
55 | Customer customer= customerService.getCustomerDetailsByEmail(email);
56 |
57 | return new ResponseEntity<>(customer,HttpStatus.ACCEPTED);
58 |
59 | }
60 |
61 | @GetMapping("/customers")
62 | public ResponseEntity> getAllCustomerHandler(){
63 |
64 |
65 | List customers= customerService.getAllCustomerDetails();
66 |
67 | return new ResponseEntity<>(customers,HttpStatus.ACCEPTED);
68 |
69 | }
70 |
71 |
72 |
73 | }
74 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT_Cors/SpringSecurityWithJwtCors/src/main/java/com/masai/controller/LoginController.java:
--------------------------------------------------------------------------------
1 | package com.masai.controller;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.http.HttpStatus;
5 | import org.springframework.http.ResponseEntity;
6 | import org.springframework.security.authentication.BadCredentialsException;
7 | import org.springframework.security.core.Authentication;
8 | import org.springframework.web.bind.annotation.GetMapping;
9 | import org.springframework.web.bind.annotation.RestController;
10 |
11 | import com.masai.model.Customer;
12 | import com.masai.repository.CustomerRepository;
13 |
14 | @RestController
15 | public class LoginController {
16 |
17 | @Autowired
18 | private CustomerRepository customerRepository;
19 |
20 | @GetMapping("/signIn")
21 | public ResponseEntity getLoggedInCustomerDetailsHandler(Authentication auth){
22 |
23 |
24 | Customer customer= customerRepository.findByEmail(auth.getName()).orElseThrow(() -> new BadCredentialsException("Invalid Username or password"));
25 |
26 | //to get the token in body, pass HttpServletResponse inside this method parameter
27 | // System.out.println(response.getHeaders(SecurityConstants.JWT_HEADER));
28 |
29 |
30 | return new ResponseEntity<>(customer, HttpStatus.ACCEPTED);
31 |
32 |
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT_Cors/SpringSecurityWithJwtCors/src/main/java/com/masai/exception/CustomerException.java:
--------------------------------------------------------------------------------
1 | package com.masai.exception;
2 |
3 | public class CustomerException extends RuntimeException {
4 |
5 | public CustomerException() {
6 | // TODO Auto-generated constructor stub
7 | }
8 |
9 | public CustomerException(String message) {
10 | super(message);
11 | }
12 |
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT_Cors/SpringSecurityWithJwtCors/src/main/java/com/masai/exception/GlobalExceptionHandler.java:
--------------------------------------------------------------------------------
1 | package com.masai.exception;
2 |
3 | import java.time.LocalDateTime;
4 |
5 | import org.springframework.http.HttpStatus;
6 | import org.springframework.http.ResponseEntity;
7 | import org.springframework.web.bind.annotation.ControllerAdvice;
8 | import org.springframework.web.bind.annotation.ExceptionHandler;
9 | import org.springframework.web.context.request.WebRequest;
10 |
11 | @ControllerAdvice
12 | public class GlobalExceptionHandler {
13 |
14 |
15 |
16 |
17 |
18 | @ExceptionHandler(CustomerException.class)
19 | public ResponseEntity customerExceptionHandler(CustomerException ce, WebRequest req){
20 |
21 |
22 | MyErrorDetails err= new MyErrorDetails();
23 | err.setTimestamp(LocalDateTime.now());
24 | err.setMessage(ce.getMessage());
25 | err.setDetails(req.getDescription(false));
26 |
27 | return new ResponseEntity(err, HttpStatus.BAD_REQUEST);
28 |
29 | }
30 |
31 |
32 |
33 | @ExceptionHandler(Exception.class)
34 | public ResponseEntity otherExceptionHandler(Exception se, WebRequest req){
35 |
36 |
37 | MyErrorDetails err= new MyErrorDetails();
38 | err.setTimestamp(LocalDateTime.now());
39 | err.setMessage(se.getMessage());
40 | err.setDetails(req.getDescription(false));
41 |
42 | return new ResponseEntity(err, HttpStatus.INTERNAL_SERVER_ERROR);
43 |
44 | }
45 |
46 |
47 |
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT_Cors/SpringSecurityWithJwtCors/src/main/java/com/masai/exception/MyErrorDetails.java:
--------------------------------------------------------------------------------
1 | package com.masai.exception;
2 |
3 | import java.time.LocalDateTime;
4 |
5 | public class MyErrorDetails {
6 |
7 | private LocalDateTime timestamp;
8 | private String message;
9 | private String details;
10 |
11 |
12 | public MyErrorDetails() {
13 | // TODO Auto-generated constructor stub
14 | }
15 |
16 |
17 | public MyErrorDetails(LocalDateTime timestamp, String message, String details) {
18 | super();
19 | this.timestamp = timestamp;
20 | this.message = message;
21 | this.details = details;
22 | }
23 |
24 |
25 | public LocalDateTime getTimestamp() {
26 | return timestamp;
27 | }
28 |
29 |
30 | public void setTimestamp(LocalDateTime timestamp) {
31 | this.timestamp = timestamp;
32 | }
33 |
34 |
35 | public String getMessage() {
36 | return message;
37 | }
38 |
39 |
40 | public void setMessage(String message) {
41 | this.message = message;
42 | }
43 |
44 |
45 | public String getDetails() {
46 | return details;
47 | }
48 |
49 |
50 | public void setDetails(String details) {
51 | this.details = details;
52 | }
53 |
54 |
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT_Cors/SpringSecurityWithJwtCors/src/main/java/com/masai/model/Customer.java:
--------------------------------------------------------------------------------
1 | package com.masai.model;
2 |
3 | import com.fasterxml.jackson.annotation.JsonProperty;
4 |
5 | import jakarta.persistence.Column;
6 | import jakarta.persistence.Entity;
7 | import jakarta.persistence.GeneratedValue;
8 | import jakarta.persistence.GenerationType;
9 | import jakarta.persistence.Id;
10 | import jakarta.persistence.UniqueConstraint;
11 | import lombok.Data;
12 |
13 | @Entity
14 | @Data
15 | public class Customer {
16 |
17 | @Id
18 | @GeneratedValue(strategy = GenerationType.AUTO)
19 | private Integer custId;
20 | private String name;
21 |
22 | @Column(unique = true)
23 | private String email;
24 | @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
25 | private String password;
26 | private String address;
27 |
28 |
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT_Cors/SpringSecurityWithJwtCors/src/main/java/com/masai/repository/CustomerRepository.java:
--------------------------------------------------------------------------------
1 | package com.masai.repository;
2 |
3 | import java.util.Optional;
4 |
5 | import org.springframework.data.jpa.repository.JpaRepository;
6 |
7 | import com.masai.model.Customer;
8 |
9 | public interface CustomerRepository extends JpaRepository{
10 |
11 |
12 | public Optional findByEmail(String email);
13 | }
14 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT_Cors/SpringSecurityWithJwtCors/src/main/java/com/masai/service/CustomerService.java:
--------------------------------------------------------------------------------
1 | package com.masai.service;
2 | import java.util.List;
3 |
4 | import com.masai.exception.CustomerException;
5 | import com.masai.model.Customer;
6 |
7 | public interface CustomerService {
8 |
9 | public Customer registerCustomer(Customer customer);
10 |
11 | public Customer getCustomerDetailsByEmail(String email)throws CustomerException;
12 |
13 | public List getAllCustomerDetails()throws CustomerException;
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT_Cors/SpringSecurityWithJwtCors/src/main/java/com/masai/service/CustomerServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.masai.service;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.stereotype.Service;
7 |
8 | import com.masai.exception.CustomerException;
9 | import com.masai.model.Customer;
10 | import com.masai.repository.CustomerRepository;
11 |
12 | @Service
13 | public class CustomerServiceImpl implements CustomerService{
14 |
15 | @Autowired
16 | private CustomerRepository customerRepository;
17 |
18 | @Override
19 | public Customer registerCustomer(Customer customer) throws CustomerException {
20 |
21 | return customerRepository.save(customer);
22 |
23 |
24 | }
25 |
26 | @Override
27 | public Customer getCustomerDetailsByEmail(String email)throws CustomerException {
28 |
29 | return customerRepository.findByEmail(email).orElseThrow(() -> new CustomerException("Customer Not found with Email: "+email));
30 | }
31 |
32 | @Override
33 | public List getAllCustomerDetails()throws CustomerException {
34 |
35 | List customers= customerRepository.findAll();
36 |
37 | if(customers.isEmpty())
38 | throw new CustomerException("No Customer find");
39 |
40 | return customers;
41 |
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT_Cors/SpringSecurityWithJwtCors/src/main/java/com/masai/service/CustomerUserDetailsService.java:
--------------------------------------------------------------------------------
1 | package com.masai.service;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Optional;
6 |
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.security.authentication.BadCredentialsException;
9 | import org.springframework.security.core.GrantedAuthority;
10 | import org.springframework.security.core.userdetails.User;
11 | import org.springframework.security.core.userdetails.UserDetails;
12 | import org.springframework.security.core.userdetails.UserDetailsService;
13 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
14 | import org.springframework.stereotype.Service;
15 |
16 | import com.masai.model.Customer;
17 | import com.masai.repository.CustomerRepository;
18 |
19 | @Service
20 | public class CustomerUserDetailsService implements UserDetailsService{
21 |
22 | @Autowired
23 | private CustomerRepository customerRepository;
24 |
25 |
26 | @Override
27 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
28 |
29 |
30 | Optional opt= customerRepository.findByEmail(username);
31 |
32 | if(opt.isPresent()) {
33 |
34 | Customer customer= opt.get();
35 |
36 | List authorities= new ArrayList<>();
37 | //authorities.add(new SimpleGrantedAuthority(customer.getRole()));
38 |
39 |
40 | return new User(customer.getEmail(), customer.getPassword(), authorities);
41 |
42 |
43 |
44 | }else
45 | throw new BadCredentialsException("User Details not found with this username: "+username);
46 |
47 |
48 |
49 |
50 |
51 | }
52 |
53 | }
54 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT_Cors/SpringSecurityWithJwtCors/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 |
2 | #db specific properties
3 | spring.datasource.url=jdbc:mysql://localhost:3306/masaidb
4 | spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
5 | spring.datasource.username=root
6 | spring.datasource.password=root
7 |
8 | #ORM s/w specific properties
9 | spring.jpa.hibernate.ddl-auto=update
10 | spring.jpa.show-sql=true
11 |
12 | #spring.security.user.name=ratan
13 | #spring.security.user.password=123
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/Spring_Security_With_JWT_Cors/SpringSecurityWithJwtCors/src/test/java/com/masai/SpringSecurityWithJwtCorsApplicationTests.java:
--------------------------------------------------------------------------------
1 | package com.masai;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.springframework.boot.test.context.SpringBootTest;
5 |
6 | @SpringBootTest
7 | class SpringSecurityWithJwtCorsApplicationTests {
8 |
9 | @Test
10 | void contextLoads() {
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/Spring_Security_With_Simple_Role_JWT2/SpringSecurityWithSimpleRoleJwt2/.gitignore:
--------------------------------------------------------------------------------
1 | HELP.md
2 | target/
3 | !.mvn/wrapper/maven-wrapper.jar
4 | !**/src/main/**/target/
5 | !**/src/test/**/target/
6 |
7 | ### STS ###
8 | .apt_generated
9 | .classpath
10 | .factorypath
11 | .project
12 | .settings
13 | .springBeans
14 | .sts4-cache
15 |
16 | ### IntelliJ IDEA ###
17 | .idea
18 | *.iws
19 | *.iml
20 | *.ipr
21 |
22 | ### NetBeans ###
23 | /nbproject/private/
24 | /nbbuild/
25 | /dist/
26 | /nbdist/
27 | /.nb-gradle/
28 | build/
29 | !**/src/main/**/build/
30 | !**/src/test/**/build/
31 |
32 | ### VS Code ###
33 | .vscode/
34 |
--------------------------------------------------------------------------------
/Spring_Security_With_Simple_Role_JWT2/SpringSecurityWithSimpleRoleJwt2/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Shubh2-0/Spring_Security/a0d45807af1cd2b3f178a105f9b61b8bfaa7c8b6/Spring_Security_With_Simple_Role_JWT2/SpringSecurityWithSimpleRoleJwt2/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/Spring_Security_With_Simple_Role_JWT2/SpringSecurityWithSimpleRoleJwt2/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip
2 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar
3 |
--------------------------------------------------------------------------------
/Spring_Security_With_Simple_Role_JWT2/SpringSecurityWithSimpleRoleJwt2/src/main/java/com/masai/SpringSecurityWithSimpleRoleJwt2Application.java:
--------------------------------------------------------------------------------
1 | package com.masai;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class SpringSecurityWithSimpleRoleJwt2Application {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(SpringSecurityWithSimpleRoleJwt2Application.class, args);
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/Spring_Security_With_Simple_Role_JWT2/SpringSecurityWithSimpleRoleJwt2/src/main/java/com/masai/Test.java:
--------------------------------------------------------------------------------
1 | package com.masai;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 |
6 | public class Test {
7 |
8 | public static void main(String[] args) {
9 | List list1= Arrays.asList();
10 | List list2= Arrays.asList();
11 |
12 | System.out.println(list1 == list2);
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/Spring_Security_With_Simple_Role_JWT2/SpringSecurityWithSimpleRoleJwt2/src/main/java/com/masai/config/AppConfig.java:
--------------------------------------------------------------------------------
1 | package com.masai.config;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.Configuration;
5 | import org.springframework.http.HttpMethod;
6 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
7 | import org.springframework.security.config.http.SessionCreationPolicy;
8 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
9 | import org.springframework.security.crypto.password.PasswordEncoder;
10 | import org.springframework.security.web.SecurityFilterChain;
11 | import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
12 |
13 | @Configuration
14 | public class AppConfig {
15 |
16 | @Bean
17 | public SecurityFilterChain springSecurityConfiguration(HttpSecurity http) throws Exception {
18 |
19 | http
20 | .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
21 | .and()
22 | .csrf().disable()
23 | .authorizeHttpRequests()
24 | .requestMatchers(HttpMethod.POST, "/customers").permitAll()
25 | .requestMatchers(HttpMethod.GET, "/customers").hasRole("ADMIN")
26 | .requestMatchers(HttpMethod.GET, "/customers/**").hasAnyRole("ADMIN","USER")
27 | .anyRequest().authenticated().and()
28 | .addFilterAfter(new JwtTokenGeneratorFilter(), BasicAuthenticationFilter.class)
29 | .addFilterBefore(new JwtTokenValidatorFilter(), BasicAuthenticationFilter.class)
30 | .formLogin()
31 | .and()
32 | .httpBasic();
33 |
34 | return http.build();
35 |
36 | }
37 |
38 | @Bean
39 | public PasswordEncoder passwordEncoder() {
40 |
41 | return new BCryptPasswordEncoder();
42 |
43 | }
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/Spring_Security_With_Simple_Role_JWT2/SpringSecurityWithSimpleRoleJwt2/src/main/java/com/masai/config/SecurityConstants.java:
--------------------------------------------------------------------------------
1 | package com.masai.config;
2 |
3 | public interface SecurityConstants {
4 |
5 | public static final String JWT_KEY ="secretsfhsfjhdkjngdfjkgfgjdlkfjsdkfjsd";
6 | public static final String JWT_HEADER = "Authorization";
7 |
8 |
9 | }
10 |
--------------------------------------------------------------------------------
/Spring_Security_With_Simple_Role_JWT2/SpringSecurityWithSimpleRoleJwt2/src/main/java/com/masai/controller/CustomerController.java:
--------------------------------------------------------------------------------
1 | package com.masai.controller;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.http.HttpStatus;
7 | import org.springframework.http.ResponseEntity;
8 | import org.springframework.security.crypto.password.PasswordEncoder;
9 | import org.springframework.web.bind.annotation.DeleteMapping;
10 | import org.springframework.web.bind.annotation.GetMapping;
11 | import org.springframework.web.bind.annotation.PathVariable;
12 | import org.springframework.web.bind.annotation.PostMapping;
13 | import org.springframework.web.bind.annotation.PutMapping;
14 | import org.springframework.web.bind.annotation.RequestBody;
15 | import org.springframework.web.bind.annotation.RestController;
16 |
17 | import com.masai.model.Customer;
18 | import com.masai.service.CustomerService;
19 |
20 | import jakarta.websocket.server.PathParam;
21 |
22 | @RestController
23 | public class CustomerController {
24 |
25 |
26 |
27 |
28 | @Autowired
29 | private CustomerService customerService;
30 |
31 | @Autowired
32 | private PasswordEncoder passwordEncoder;
33 |
34 |
35 | @GetMapping("/hello")
36 | public String testHandler() {
37 | return "Welcome to Spring Security";
38 | }
39 |
40 | @PostMapping("/customers")
41 | public ResponseEntity saveCustomerHandler(@RequestBody Customer customer){
42 |
43 | customer.setRole("ROLE_"+customer.getRole().toUpperCase());
44 |
45 | customer.setPassword(passwordEncoder.encode(customer.getPassword()));
46 |
47 | Customer registeredCustomer= customerService.registerCustomer(customer);
48 |
49 | return new ResponseEntity<>(registeredCustomer,HttpStatus.ACCEPTED);
50 |
51 | }
52 |
53 | @GetMapping("/customers/{email}")
54 | public ResponseEntity getCustomerByEmailHandler(@PathVariable("email") String email){
55 |
56 |
57 | Customer customer= customerService.getCustomerDetailsByEmail(email);
58 |
59 | return new ResponseEntity<>(customer,HttpStatus.ACCEPTED);
60 |
61 | }
62 |
63 | @GetMapping("/customers")
64 | public ResponseEntity> getAllCustomerHandler(){
65 |
66 |
67 | List customers= customerService.getAllCustomerDetails();
68 |
69 | return new ResponseEntity<>(customers,HttpStatus.ACCEPTED);
70 |
71 | }
72 |
73 |
74 |
75 | }
76 |
--------------------------------------------------------------------------------
/Spring_Security_With_Simple_Role_JWT2/SpringSecurityWithSimpleRoleJwt2/src/main/java/com/masai/controller/LoginController.java:
--------------------------------------------------------------------------------
1 | package com.masai.controller;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.http.HttpStatus;
5 | import org.springframework.http.ResponseEntity;
6 | import org.springframework.security.authentication.BadCredentialsException;
7 | import org.springframework.security.core.Authentication;
8 | import org.springframework.web.bind.annotation.GetMapping;
9 | import org.springframework.web.bind.annotation.RestController;
10 |
11 | import com.masai.model.Customer;
12 | import com.masai.repository.CustomerRepository;
13 |
14 | @RestController
15 | public class LoginController {
16 |
17 | @Autowired
18 | private CustomerRepository customerRepository;
19 |
20 | @GetMapping("/signIn")
21 | public ResponseEntity getLoggedInCustomerDetailsHandler(Authentication auth){
22 |
23 |
24 | Customer customer= customerRepository.findByEmail(auth.getName()).orElseThrow(() -> new BadCredentialsException("Invalid Username or password"));
25 |
26 | //to get the token in body, pass HttpServletResponse inside this method parameter
27 | // System.out.println(response.getHeaders(SecurityConstants.JWT_HEADER));
28 |
29 |
30 | return new ResponseEntity<>(customer, HttpStatus.ACCEPTED);
31 |
32 |
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/Spring_Security_With_Simple_Role_JWT2/SpringSecurityWithSimpleRoleJwt2/src/main/java/com/masai/exception/CustomerException.java:
--------------------------------------------------------------------------------
1 | package com.masai.exception;
2 |
3 | public class CustomerException extends RuntimeException {
4 |
5 | public CustomerException() {
6 | // TODO Auto-generated constructor stub
7 | }
8 |
9 | public CustomerException(String message) {
10 | super(message);
11 | }
12 |
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/Spring_Security_With_Simple_Role_JWT2/SpringSecurityWithSimpleRoleJwt2/src/main/java/com/masai/exception/GlobalExceptionHandler.java:
--------------------------------------------------------------------------------
1 | package com.masai.exception;
2 |
3 | import java.time.LocalDateTime;
4 |
5 | import org.springframework.http.HttpStatus;
6 | import org.springframework.http.ResponseEntity;
7 | import org.springframework.web.bind.annotation.ControllerAdvice;
8 | import org.springframework.web.bind.annotation.ExceptionHandler;
9 | import org.springframework.web.context.request.WebRequest;
10 |
11 | @ControllerAdvice
12 | public class GlobalExceptionHandler {
13 |
14 |
15 |
16 |
17 |
18 | @ExceptionHandler(CustomerException.class)
19 | public ResponseEntity customerExceptionHandler(CustomerException ce, WebRequest req){
20 |
21 |
22 | MyErrorDetails err= new MyErrorDetails();
23 | err.setTimestamp(LocalDateTime.now());
24 | err.setMessage(ce.getMessage());
25 | err.setDetails(req.getDescription(false));
26 |
27 | return new ResponseEntity(err, HttpStatus.BAD_REQUEST);
28 |
29 | }
30 |
31 |
32 |
33 | @ExceptionHandler(Exception.class)
34 | public ResponseEntity otherExceptionHandler(Exception se, WebRequest req){
35 |
36 |
37 | MyErrorDetails err= new MyErrorDetails();
38 | err.setTimestamp(LocalDateTime.now());
39 | err.setMessage(se.getMessage());
40 | err.setDetails(req.getDescription(false));
41 |
42 | return new ResponseEntity(err, HttpStatus.INTERNAL_SERVER_ERROR);
43 |
44 | }
45 |
46 |
47 |
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/Spring_Security_With_Simple_Role_JWT2/SpringSecurityWithSimpleRoleJwt2/src/main/java/com/masai/exception/MyErrorDetails.java:
--------------------------------------------------------------------------------
1 | package com.masai.exception;
2 |
3 | import java.time.LocalDateTime;
4 |
5 | public class MyErrorDetails {
6 |
7 | private LocalDateTime timestamp;
8 | private String message;
9 | private String details;
10 |
11 |
12 | public MyErrorDetails() {
13 | // TODO Auto-generated constructor stub
14 | }
15 |
16 |
17 | public MyErrorDetails(LocalDateTime timestamp, String message, String details) {
18 | super();
19 | this.timestamp = timestamp;
20 | this.message = message;
21 | this.details = details;
22 | }
23 |
24 |
25 | public LocalDateTime getTimestamp() {
26 | return timestamp;
27 | }
28 |
29 |
30 | public void setTimestamp(LocalDateTime timestamp) {
31 | this.timestamp = timestamp;
32 | }
33 |
34 |
35 | public String getMessage() {
36 | return message;
37 | }
38 |
39 |
40 | public void setMessage(String message) {
41 | this.message = message;
42 | }
43 |
44 |
45 | public String getDetails() {
46 | return details;
47 | }
48 |
49 |
50 | public void setDetails(String details) {
51 | this.details = details;
52 | }
53 |
54 |
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/Spring_Security_With_Simple_Role_JWT2/SpringSecurityWithSimpleRoleJwt2/src/main/java/com/masai/model/Customer.java:
--------------------------------------------------------------------------------
1 | package com.masai.model;
2 |
3 | import com.fasterxml.jackson.annotation.JsonProperty;
4 |
5 | import jakarta.persistence.Column;
6 | import jakarta.persistence.Entity;
7 | import jakarta.persistence.GeneratedValue;
8 | import jakarta.persistence.GenerationType;
9 | import jakarta.persistence.Id;
10 | import jakarta.persistence.UniqueConstraint;
11 | import lombok.Data;
12 |
13 | @Entity
14 | @Data
15 | public class Customer {
16 |
17 | @Id
18 | @GeneratedValue(strategy = GenerationType.AUTO)
19 | private Integer custId;
20 | private String name;
21 |
22 | @Column(unique = true)
23 | private String email;
24 | @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
25 | private String password;
26 | private String address;
27 |
28 | private String role;
29 |
30 |
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/Spring_Security_With_Simple_Role_JWT2/SpringSecurityWithSimpleRoleJwt2/src/main/java/com/masai/repository/CustomerRepository.java:
--------------------------------------------------------------------------------
1 | package com.masai.repository;
2 |
3 | import java.util.Optional;
4 |
5 | import org.springframework.data.jpa.repository.JpaRepository;
6 |
7 | import com.masai.model.Customer;
8 |
9 | public interface CustomerRepository extends JpaRepository{
10 |
11 |
12 | public Optional findByEmail(String email);
13 | }
14 |
--------------------------------------------------------------------------------
/Spring_Security_With_Simple_Role_JWT2/SpringSecurityWithSimpleRoleJwt2/src/main/java/com/masai/service/CustomerService.java:
--------------------------------------------------------------------------------
1 | package com.masai.service;
2 | import java.util.List;
3 |
4 | import com.masai.exception.CustomerException;
5 | import com.masai.model.Customer;
6 |
7 | public interface CustomerService {
8 |
9 | public Customer registerCustomer(Customer customer);
10 |
11 | public Customer getCustomerDetailsByEmail(String email)throws CustomerException;
12 |
13 | public List getAllCustomerDetails()throws CustomerException;
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/Spring_Security_With_Simple_Role_JWT2/SpringSecurityWithSimpleRoleJwt2/src/main/java/com/masai/service/CustomerServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.masai.service;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.stereotype.Service;
7 |
8 | import com.masai.exception.CustomerException;
9 | import com.masai.model.Customer;
10 | import com.masai.repository.CustomerRepository;
11 |
12 | @Service
13 | public class CustomerServiceImpl implements CustomerService{
14 |
15 | @Autowired
16 | private CustomerRepository customerRepository;
17 |
18 | @Override
19 | public Customer registerCustomer(Customer customer) throws CustomerException {
20 |
21 | return customerRepository.save(customer);
22 |
23 |
24 | }
25 |
26 | @Override
27 | public Customer getCustomerDetailsByEmail(String email)throws CustomerException {
28 |
29 | return customerRepository.findByEmail(email).orElseThrow(() -> new CustomerException("Customer Not found with Email: "+email));
30 | }
31 |
32 | @Override
33 | public List getAllCustomerDetails()throws CustomerException {
34 |
35 | List customers= customerRepository.findAll();
36 |
37 | if(customers.isEmpty())
38 | throw new CustomerException("No Customer find");
39 |
40 | return customers;
41 |
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/Spring_Security_With_Simple_Role_JWT2/SpringSecurityWithSimpleRoleJwt2/src/main/java/com/masai/service/CustomerUserDetailsService.java:
--------------------------------------------------------------------------------
1 | package com.masai.service;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Optional;
6 |
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.security.authentication.BadCredentialsException;
9 | import org.springframework.security.core.GrantedAuthority;
10 | import org.springframework.security.core.authority.SimpleGrantedAuthority;
11 | import org.springframework.security.core.userdetails.User;
12 | import org.springframework.security.core.userdetails.UserDetails;
13 | import org.springframework.security.core.userdetails.UserDetailsService;
14 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
15 | import org.springframework.stereotype.Service;
16 |
17 | import com.masai.model.Customer;
18 | import com.masai.repository.CustomerRepository;
19 |
20 | @Service
21 | public class CustomerUserDetailsService implements UserDetailsService{
22 |
23 | @Autowired
24 | private CustomerRepository customerRepository;
25 |
26 |
27 | @Override
28 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
29 |
30 |
31 | Optional opt= customerRepository.findByEmail(username);
32 |
33 | if(opt.isPresent()) {
34 |
35 | Customer customer= opt.get();
36 |
37 | List authorities= new ArrayList<>();
38 | SimpleGrantedAuthority sga= new SimpleGrantedAuthority(customer.getRole());
39 | authorities.add(sga);
40 |
41 |
42 | return new User(customer.getEmail(), customer.getPassword(), authorities);
43 |
44 |
45 |
46 |
47 | }else
48 | throw new BadCredentialsException("User Details not found with this username: "+username);
49 |
50 |
51 |
52 |
53 |
54 | }
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/Spring_Security_With_Simple_Role_JWT2/SpringSecurityWithSimpleRoleJwt2/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 |
2 | #db specific properties
3 | spring.datasource.url=jdbc:mysql://localhost:3306/masaidb
4 | spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
5 | spring.datasource.username=root
6 | spring.datasource.password=root
7 |
8 | #ORM s/w specific properties
9 | spring.jpa.hibernate.ddl-auto=update
10 | spring.jpa.show-sql=true
11 |
12 | #spring.security.user.name=ratan
13 | #spring.security.user.password=123
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/Spring_Security_With_Simple_Role_JWT2/SpringSecurityWithSimpleRoleJwt2/src/test/java/com/masai/SpringSecurityWithSimpleRoleJwt2ApplicationTests.java:
--------------------------------------------------------------------------------
1 | package com.masai;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.springframework.boot.test.context.SpringBootTest;
5 |
6 | @SpringBootTest
7 | class SpringSecurityWithSimpleRoleJwt2ApplicationTests {
8 |
9 | @Test
10 | void contextLoads() {
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT/.gitignore:
--------------------------------------------------------------------------------
1 | HELP.md
2 | target/
3 | !.mvn/wrapper/maven-wrapper.jar
4 | !**/src/main/**/target/
5 | !**/src/test/**/target/
6 |
7 | ### STS ###
8 | .apt_generated
9 | .classpath
10 | .factorypath
11 | .project
12 | .settings
13 | .springBeans
14 | .sts4-cache
15 |
16 | ### IntelliJ IDEA ###
17 | .idea
18 | *.iws
19 | *.iml
20 | *.ipr
21 |
22 | ### NetBeans ###
23 | /nbproject/private/
24 | /nbbuild/
25 | /dist/
26 | /nbdist/
27 | /.nb-gradle/
28 | build/
29 | !**/src/main/**/build/
30 | !**/src/test/**/build/
31 |
32 | ### VS Code ###
33 | .vscode/
34 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Shubh2-0/Spring_Security/a0d45807af1cd2b3f178a105f9b61b8bfaa7c8b6/Spring_Security_Without_JWT/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.3/apache-maven-3.9.3-bin.zip
2 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar
3 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | org.springframework.boot
8 | spring-boot-starter-parent
9 | 3.1.1
10 |
11 |
12 | com.masai
13 | Spring_Security_Without_JWT
14 | 0.0.1-SNAPSHOT
15 | Spring_Security_Without_JWT
16 | Demo project for Spring Boot Security Without JWT
17 |
18 | 17
19 |
20 |
21 |
22 | org.springframework.boot
23 | spring-boot-starter-data-jpa
24 |
25 |
26 | org.springframework.boot
27 | spring-boot-starter-security
28 |
29 |
30 | org.springframework.boot
31 | spring-boot-starter-web
32 |
33 |
34 |
35 | org.springframework.boot
36 | spring-boot-devtools
37 | runtime
38 | true
39 |
40 |
41 | com.mysql
42 | mysql-connector-j
43 | runtime
44 |
45 |
46 | org.projectlombok
47 | lombok
48 | true
49 |
50 |
51 | org.springframework.boot
52 | spring-boot-starter-test
53 | test
54 |
55 |
56 | org.springframework.boot
57 | spring-boot-starter-security
58 |
59 |
60 | org.springframework.security
61 | spring-security-test
62 | test
63 |
64 |
65 |
66 |
67 |
68 |
69 | org.springframework.boot
70 | spring-boot-maven-plugin
71 |
72 |
73 |
74 | org.projectlombok
75 | lombok
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT/src/main/java/com/masai/SpringSecurityWithoutJwtApplication.java:
--------------------------------------------------------------------------------
1 | package com.masai;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class SpringSecurityWithoutJwtApplication {
8 |
9 | /*
10 | * MAIN INTERFACE WHERE OUR APPLICATION IS STARTED THIS CLASS BY DEFAULT CREATED
11 | * BY SPRING BOOT
12 | */
13 |
14 | public static void main(String[] args) {
15 | SpringApplication.run(SpringSecurityWithoutJwtApplication.class, args);
16 | }
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT/src/main/java/com/masai/config/AppConfig.java:
--------------------------------------------------------------------------------
1 | package com.masai.config;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.Configuration;
5 | import org.springframework.http.HttpMethod;
6 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
7 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
8 | import org.springframework.security.crypto.password.PasswordEncoder;
9 | import org.springframework.security.web.SecurityFilterChain;
10 |
11 | @Configuration
12 | public class AppConfig {
13 |
14 | /*
15 | * HERE WE CREATE OUR OWN SECURITY CHAIN FILTER THAT AUTHENTICATES THE USER
16 | * MEANS HERE WE CUSTOMIZE THE CONFIGURATION AND ALSO HERE WE USE @Bean
17 | * ANNOTATION SO IT'S SHOULD REGISTOR WITH THE SPRING CONTAINER
18 | */
19 | @Bean
20 | public SecurityFilterChain springSecurityConfiguration(HttpSecurity http) throws Exception {
21 |
22 | /*
23 | * HERE OUR ALL THE REQUEST IS AUTHORISED
24 | */
25 | http.authorizeHttpRequests()
26 | /*
27 | * HERE WE GIVE THAT PARTICULAR END POINT(APIs) TO ACCESS ANYONE MEANS THIS API
28 | * BY AUTHORISED CLIENTS ALSO AND UNAUTHORISED CLIENT ALSO WHITE LISTING THIS
29 | * API IF WE HAVE TWO END POINTS WITH SAME NAME BUT DIFFERENT GETTING METHOD SO
30 | * WE HAVE GIVE THE TYPE ALSO
31 | */
32 | .requestMatchers("/customers").permitAll()
33 | /*
34 | * HERE WE GIVE END ALL THE POINT(APIs)[NOT INCLUDE THAT APIs WHERE WE GIVE
35 | * .permillAll() ] TO ACCESS BY AUTHORISED CLIENTS ONLY
36 | */
37 | .anyRequest().authenticated()
38 | /*
39 | * SOME EXTRA INFORMATION OR SECURITY FEATURES
40 | */
41 | .and()
42 | /*
43 | * HERE WE DISABLE THE csrf (Cross-Site Request Forgery) IF WE EBBALED THE
44 | * SPRING SECURITY FEATURE IN OUR APPLICATION IT WILL STOP ANY KIND OF POST
45 | * REQUEST AND PUT REQUEST WHICH WILL SHARE SOME DATA BY DEFUALT IT IS ENBLED IN
46 | * THE SPRING SECURITY BUT WE HAVE TO DISABLED THIS
47 | */
48 | .csrf().disable()
49 | /*
50 | * THIS IS BASICALLY USED FOR WEB BROSWER WHERE WE CAN SEE THE LOGIN PAGE WHICH
51 | * IS AUTOMATICALLY CREATED BY SPRING SECURITY
52 | */
53 | .formLogin().and()
54 | /*
55 | * THIS IS BASICALLY USE FOR POSTMEN AND SOME JAVASCRIPT
56 | */
57 | .httpBasic();
58 |
59 | /*
60 | * THIS STATEMENT WILL RETURN THE SECURITY CHAIN OBJECT
61 | */
62 | return http.build();
63 |
64 | }
65 |
66 | /*
67 | * HERE THIS METHOD IS RESponSiBLe fOR RETURNING THE PasswordEncoder OBJECT
68 | * WHERE WE CONVERTED THE USER PASSWORD INTO Base64 Encoded VERSION AND ALSO
69 | * HERE WE USE @Bean ANNOTATION SO IT'S SHOULD REGISTOR WITH THE SPRING
70 | * CONTAINER
71 | */
72 | @Bean
73 | public PasswordEncoder passwordEncoder() {
74 |
75 | return new BCryptPasswordEncoder();
76 | }
77 |
78 | }
79 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT/src/main/java/com/masai/controller/CustomerController.java:
--------------------------------------------------------------------------------
1 | package com.masai.controller;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.http.HttpStatus;
7 | import org.springframework.http.ResponseEntity;
8 | import org.springframework.security.crypto.password.PasswordEncoder;
9 | import org.springframework.web.bind.annotation.GetMapping;
10 | import org.springframework.web.bind.annotation.PathVariable;
11 | import org.springframework.web.bind.annotation.PostMapping;
12 | import org.springframework.web.bind.annotation.RequestBody;
13 | import org.springframework.web.bind.annotation.RestController;
14 |
15 | import com.masai.exception.CustomerException;
16 | import com.masai.model.Customer;
17 | import com.masai.service.CustomerService;
18 |
19 | /*
20 | OUR RESTCONTROLLER WHERE WE CREATE
21 | ENDPOINTS(APIs)
22 | */
23 |
24 | @RestController
25 | public class CustomerController {
26 |
27 | @Autowired
28 | private CustomerService customerService;
29 |
30 | /*
31 | * THIS OBJECT IS RESPONSIBLE FOR CONVERTED THE USER PASSWORD INTO base64
32 | * ENCODED VERSION
33 | */
34 | @Autowired
35 | private PasswordEncoder passwordEncoder;
36 |
37 | @GetMapping("/learn")
38 | public String testHandler() {
39 |
40 | return "LEARNING SPRING SECURITY";
41 |
42 | }
43 |
44 | @PostMapping("/customers")
45 | public ResponseEntity addCustomerHandler(@RequestBody Customer customer) throws CustomerException {
46 |
47 | // HERE WE CHANGE THE NORMAL USER PASSWORD INTO base64 encoded VERSION
48 | customer.setPassword(passwordEncoder.encode(customer.getPassword()));
49 |
50 | Customer registorCustomer = customerService.addCustomer(customer);
51 |
52 | return new ResponseEntity(registorCustomer, HttpStatus.ACCEPTED);
53 |
54 | }
55 |
56 | @GetMapping("/customers/{email}")
57 | public ResponseEntity getCustomerbyEmailHandler(@PathVariable("email") String email)
58 | throws CustomerException {
59 |
60 | return new ResponseEntity(customerService.getCustomerByEmail(email), HttpStatus.ACCEPTED);
61 |
62 | }
63 |
64 | @GetMapping("/customers/all")
65 | public ResponseEntity> getAllCustomerHandler() throws CustomerException {
66 |
67 | return new ResponseEntity>(customerService.getAllCustomer(), HttpStatus.ACCEPTED);
68 |
69 | }
70 |
71 | @GetMapping("/customers/address/{address}")
72 | public ResponseEntity> getAllCustomerByAddressHandler(@PathVariable ("address") String address ) throws CustomerException{
73 |
74 | return new ResponseEntity>(customerService.getCustomerByAddress(address), HttpStatus.ACCEPTED);
75 | }
76 |
77 | }
78 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT/src/main/java/com/masai/controller/CustomerLoginController.java:
--------------------------------------------------------------------------------
1 | package com.masai.controller;
2 |
3 |
4 | import org.springframework.beans.factory.annotation.Autowired;
5 | import org.springframework.http.HttpStatus;
6 | import org.springframework.http.ResponseEntity;
7 | import org.springframework.security.authentication.BadCredentialsException;
8 | import org.springframework.security.core.Authentication;
9 | import org.springframework.web.bind.annotation.GetMapping;
10 | import org.springframework.web.bind.annotation.RestController;
11 |
12 | import com.masai.model.Customer;
13 | import com.masai.repository.CustomerRepository;
14 |
15 | @RestController
16 | public class CustomerLoginController {
17 |
18 | @Autowired
19 | private CustomerRepository customerRepository;
20 |
21 |
22 | /*
23 | * HERE WE CREATED ONE ENDPOINT FOR signIn THE USER
24 | * IT WILL TAKE Authentication object
25 | * IN Authentication object WE HAVE THE USERNAME AND PASSWORD OF THE USER
26 | * IN WHICH WE CAN FIND THE USER BY THIER USERNAME
27 | */
28 | @GetMapping("/signIn")
29 | public ResponseEntity getLoggedInCustomerHandler(Authentication auth){
30 |
31 | System.out.println("AUTHENTICATION OBJECT :"+ auth);
32 |
33 | /* IN Authentication object WE HAVE SOME METHOD WHERE WE CAN ACCESS THE USER INFORMATION
34 | * ONE OF THEM ARE getName() WHICH BASICALLY return THE USER username
35 | *
36 | */
37 | Customer customer = customerRepository.findByEmail(auth.getName()).orElseThrow((() -> new BadCredentialsException("invalid email")));
38 |
39 |
40 | return new ResponseEntity(customer,HttpStatus.ACCEPTED);
41 |
42 | }
43 |
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT/src/main/java/com/masai/exception/CustomError.java:
--------------------------------------------------------------------------------
1 | package com.masai.exception;
2 |
3 | import java.time.LocalDateTime;
4 |
5 | import lombok.AllArgsConstructor;
6 | import lombok.Data;
7 | import lombok.NoArgsConstructor;
8 |
9 | @Data
10 | @NoArgsConstructor
11 | @AllArgsConstructor
12 |
13 | /*
14 | * HERE WE CREATED OUR OWN CUSTOME EXCEPTION OR ERROR IN SIMPLE BODY OF OUR
15 | * ERROR
16 | */
17 | public class CustomError {
18 |
19 | private LocalDateTime time;
20 | private String message;
21 | private String details;
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT/src/main/java/com/masai/exception/CustomerException.java:
--------------------------------------------------------------------------------
1 | package com.masai.exception;
2 |
3 | public class CustomerException extends Exception {
4 |
5 | public CustomerException(String m) {
6 |
7 | super(m);
8 | }
9 |
10 | }
11 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT/src/main/java/com/masai/exception/GlobalExceptionHandler.java:
--------------------------------------------------------------------------------
1 | package com.masai.exception;
2 |
3 | import java.time.LocalDateTime;
4 |
5 | import org.springframework.http.HttpStatus;
6 | import org.springframework.http.ResponseEntity;
7 | import org.springframework.web.bind.annotation.ControllerAdvice;
8 | import org.springframework.web.bind.annotation.ExceptionHandler;
9 | import org.springframework.web.context.request.WebRequest;
10 |
11 | @ControllerAdvice
12 | public class GlobalExceptionHandler {
13 |
14 | /*
15 | * HERE WE CREATE OUR OWN CUSTOME ERROR SO WHEN ANY EEXCEPTION ACCUR SO THAT
16 | * EXCEPTION HANDLER HANDLE THAT SITUATION
17 | *
18 | */
19 | @ExceptionHandler(CustomerException.class)
20 | public ResponseEntity customerExceptionHandler(CustomerException e, WebRequest req) {
21 |
22 | CustomError error = new CustomError();
23 | error.setTime(LocalDateTime.now());
24 | error.setMessage(e.getMessage());
25 | error.setDetails(req.getDescription(false));
26 |
27 | return new ResponseEntity(error, HttpStatus.BAD_REQUEST);
28 |
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT/src/main/java/com/masai/model/Customer.java:
--------------------------------------------------------------------------------
1 | package com.masai.model;
2 |
3 | import com.fasterxml.jackson.annotation.JsonProperty;
4 |
5 | import jakarta.annotation.Generated;
6 | import jakarta.persistence.Column;
7 | import jakarta.persistence.Entity;
8 | import jakarta.persistence.GeneratedValue;
9 | import jakarta.persistence.GenerationType;
10 | import jakarta.persistence.Id;
11 | import lombok.AllArgsConstructor;
12 | import lombok.Data;
13 | import lombok.NoArgsConstructor;
14 |
15 | @Entity
16 | @Data
17 | @NoArgsConstructor
18 | @AllArgsConstructor
19 | public class Customer {
20 |
21 | @Id
22 | @GeneratedValue(strategy = GenerationType.AUTO)
23 | private Integer Id;
24 |
25 | private String name;
26 |
27 | @Column(unique = true)
28 | private String email;
29 |
30 | /*
31 | * AT THE TIME OF FETCHING ANY USER WE CAN'T SEE THIER PASSWORD BECUASE OF THIS
32 | * PROPERTY
33 | */
34 | @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
35 | private String password;
36 |
37 | private String address;
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT/src/main/java/com/masai/repository/CustomerRepository.java:
--------------------------------------------------------------------------------
1 | package com.masai.repository;
2 |
3 | import java.util.List;
4 | import java.util.Optional;
5 |
6 | import org.springframework.data.jpa.repository.JpaRepository;
7 |
8 | import com.masai.model.Customer;
9 |
10 | public interface CustomerRepository extends JpaRepository {
11 |
12 | /*
13 | * HERE WE CREATE A METHOD WHERE WE CAN FIND THE USER BY THIER EMAIL ADDRESS AND
14 | * ALSO HERE WE USE Optional CLAS FOR ACCHIEVING THE FUNCTIONAL WAY
15 | */
16 | public Optional findByEmail(String email);
17 |
18 | /*
19 | * HERE WE CREATE A METHOD WHERE WE CAN FIND THE USER BY THIER ADDRESS ALSO
20 | */
21 | public Optional> findByAddress(String address);
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT/src/main/java/com/masai/service/CustomerService.java:
--------------------------------------------------------------------------------
1 | package com.masai.service;
2 |
3 | import java.util.List;
4 |
5 | import com.masai.exception.CustomerException;
6 | import com.masai.model.Customer;
7 |
8 | public interface CustomerService {
9 |
10 | Customer addCustomer(Customer customer) throws CustomerException;
11 |
12 | Customer getCustomerByEmail(String email) throws CustomerException;
13 |
14 | List getAllCustomer() throws CustomerException;
15 |
16 | List getCustomerByAddress(String address) throws CustomerException;
17 | }
18 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT/src/main/java/com/masai/service/CustomerServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.masai.service;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.stereotype.Service;
7 |
8 | import com.masai.exception.CustomerException;
9 | import com.masai.model.Customer;
10 | import com.masai.repository.CustomerRepository;
11 |
12 | @Service
13 | public class CustomerServiceImpl implements CustomerService {
14 |
15 | @Autowired
16 | private CustomerRepository customerRepository;
17 |
18 | @Override
19 | public Customer addCustomer(Customer customer) throws CustomerException {
20 |
21 | return customerRepository.save(customer);
22 |
23 | }
24 |
25 | @Override
26 | public Customer getCustomerByEmail(String email) throws CustomerException {
27 |
28 | /*
29 | * HERE WE USE FUNCTIONAL WHY TO RETURN THE CUSTOMER OBJECT IT'S POSSIBLE BY THE
30 | * HELP OF Optional CLASS IF THE OPTIONAL IS NOT EMPTY THAN IT RETURN THE
31 | * CUSTOMER OBJECT OTHER WISE IT THROW THE CustomerException IT ISE VERY SIMPLE
32 | * AND EASY
33 | *
34 | */
35 | return customerRepository.findByEmail(email)
36 | .orElseThrow(() -> new CustomerException("Customer not found by this email : " + email));
37 |
38 | }
39 |
40 | @Override
41 | public List getAllCustomer() throws CustomerException {
42 |
43 | List customers = customerRepository.findAll();
44 |
45 | if (customers.isEmpty())
46 | throw new CustomerException("no customer found");
47 |
48 | return customers;
49 |
50 | }
51 |
52 | @Override
53 | public List getCustomerByAddress(String address) throws CustomerException {
54 |
55 | return customerRepository.findByAddress(address)
56 | .orElseThrow(() -> new CustomerException("No customer found we that address :" + address));
57 |
58 | }
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT/src/main/java/com/masai/service/CustomerUserDetailsService.java:
--------------------------------------------------------------------------------
1 | package com.masai.service;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Optional;
6 |
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.security.authentication.BadCredentialsException;
9 | import org.springframework.security.core.GrantedAuthority;
10 | import org.springframework.security.core.userdetails.User;
11 | import org.springframework.security.core.userdetails.UserDetails;
12 | import org.springframework.security.core.userdetails.UserDetailsService;
13 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
14 | import org.springframework.stereotype.Service;
15 |
16 | import com.masai.model.Customer;
17 | import com.masai.repository.CustomerRepository;
18 |
19 | /*
20 | * SO HERE WE CREATED OUR OWN UserDetailsService CLASS
21 | * WHICH ARE RESPONSIBLE NFOR Authorized OUR USERS
22 | * BY DEFUALT IT USES InMemoryDeatailsService
23 | * FOR AUTHENTICATION OUR USERS
24 | *
25 | *
26 | */
27 | @Service
28 | public class CustomerUserDetailsService implements UserDetailsService {
29 |
30 | @Autowired
31 | private CustomerRepository customerRepository;
32 |
33 | @Override
34 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
35 |
36 | Optional optional = customerRepository.findByEmail(username);
37 |
38 | if (optional.isPresent()) {
39 |
40 | Customer customer = optional.get();
41 |
42 | /*
43 | * HERE WE DECLARED SOME AUTHORITY THAT BELONGS TO THAT USER LIKE ROLE BASED
44 | * PERMISSIONS, FUNTIONALITY AND SO ON
45 | */
46 | List authorities = new ArrayList<>();
47 |
48 | return new User(customer.getEmail(), customer.getPassword(), authorities);
49 |
50 | } else
51 |
52 | throw new BadCredentialsException("User not found with this email :" + username);
53 |
54 | }
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | #db specific properties
2 | spring.datasource.url=jdbc:mysql://localhost:3306/prac
3 | spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
4 | spring.datasource.username=root
5 | spring.datasource.password=root
6 |
7 | #ORM s/w specific properties
8 | spring.jpa.hibernate.ddl-auto=update
9 | spring.jpa.show-sql=true
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT/src/test/java/com/masai/SpringSecurityWithoutJwtApplicationTests.java:
--------------------------------------------------------------------------------
1 | package com.masai;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.springframework.boot.test.context.SpringBootTest;
5 |
6 | @SpringBootTest
7 | class SpringSecurityWithoutJwtApplicationTests {
8 |
9 | @Test
10 | void contextLoads() {
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT2/SpringSecurityWithoutJwt/.gitignore:
--------------------------------------------------------------------------------
1 | HELP.md
2 | target/
3 | !.mvn/wrapper/maven-wrapper.jar
4 | !**/src/main/**/target/
5 | !**/src/test/**/target/
6 |
7 | ### STS ###
8 | .apt_generated
9 | .classpath
10 | .factorypath
11 | .project
12 | .settings
13 | .springBeans
14 | .sts4-cache
15 |
16 | ### IntelliJ IDEA ###
17 | .idea
18 | *.iws
19 | *.iml
20 | *.ipr
21 |
22 | ### NetBeans ###
23 | /nbproject/private/
24 | /nbbuild/
25 | /dist/
26 | /nbdist/
27 | /.nb-gradle/
28 | build/
29 | !**/src/main/**/build/
30 | !**/src/test/**/build/
31 |
32 | ### VS Code ###
33 | .vscode/
34 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT2/SpringSecurityWithoutJwt/.mvn/wrapper/maven-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Shubh2-0/Spring_Security/a0d45807af1cd2b3f178a105f9b61b8bfaa7c8b6/Spring_Security_Without_JWT2/SpringSecurityWithoutJwt/.mvn/wrapper/maven-wrapper.jar
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT2/SpringSecurityWithoutJwt/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip
2 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar
3 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT2/SpringSecurityWithoutJwt/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | org.springframework.boot
7 | spring-boot-starter-parent
8 | 3.0.1
9 |
10 |
11 | com.example
12 | SpringSecurityWithoutJwt
13 | 0.0.1-SNAPSHOT
14 | SpringSecurityWithoutJwt
15 | Demo project for Spring Boot
16 |
17 | 17
18 |
19 |
20 |
21 | org.springframework.boot
22 | spring-boot-starter-data-jpa
23 |
24 |
25 | org.springframework.boot
26 | spring-boot-starter-security
27 |
28 |
29 | org.springframework.boot
30 | spring-boot-starter-web
31 |
32 |
33 |
34 | org.springframework.boot
35 | spring-boot-devtools
36 | runtime
37 | true
38 |
39 |
40 | com.mysql
41 | mysql-connector-j
42 | runtime
43 |
44 |
45 | org.projectlombok
46 | lombok
47 | true
48 |
49 |
50 | org.springframework.boot
51 | spring-boot-starter-test
52 | test
53 |
54 |
55 | org.springframework.security
56 | spring-security-test
57 | test
58 |
59 |
60 |
61 |
62 |
63 |
64 | org.springframework.boot
65 | spring-boot-maven-plugin
66 |
67 |
68 |
69 | org.projectlombok
70 | lombok
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT2/SpringSecurityWithoutJwt/src/main/java/com/masai/SpringSecurityWithoutJwtApplication.java:
--------------------------------------------------------------------------------
1 | package com.masai;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class SpringSecurityWithoutJwtApplication {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(SpringSecurityWithoutJwtApplication.class, args);
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT2/SpringSecurityWithoutJwt/src/main/java/com/masai/config/AppConfig.java:
--------------------------------------------------------------------------------
1 | package com.masai.config;
2 |
3 | import org.springframework.context.annotation.Bean;
4 | import org.springframework.context.annotation.Configuration;
5 | import org.springframework.http.HttpMethod;
6 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
7 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
8 | import org.springframework.security.crypto.password.PasswordEncoder;
9 | import org.springframework.security.web.SecurityFilterChain;
10 |
11 | @Configuration
12 | public class AppConfig {
13 |
14 | @Bean
15 | public SecurityFilterChain springSecurityConfiguration(HttpSecurity http) throws Exception {
16 |
17 | http.authorizeHttpRequests()
18 | .requestMatchers(HttpMethod.POST, "/customers").permitAll()
19 | .anyRequest()
20 | .authenticated()
21 | .and()
22 | .csrf().disable().formLogin().and().httpBasic();
23 |
24 | return http.build();
25 |
26 | }
27 |
28 | @Bean
29 | public PasswordEncoder passwordEncoder() {
30 |
31 | return new BCryptPasswordEncoder();
32 |
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT2/SpringSecurityWithoutJwt/src/main/java/com/masai/controller/CustomerController.java:
--------------------------------------------------------------------------------
1 | package com.masai.controller;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.http.HttpStatus;
7 | import org.springframework.http.ResponseEntity;
8 | import org.springframework.security.crypto.password.PasswordEncoder;
9 | import org.springframework.web.bind.annotation.DeleteMapping;
10 | import org.springframework.web.bind.annotation.GetMapping;
11 | import org.springframework.web.bind.annotation.PathVariable;
12 | import org.springframework.web.bind.annotation.PostMapping;
13 | import org.springframework.web.bind.annotation.PutMapping;
14 | import org.springframework.web.bind.annotation.RequestBody;
15 | import org.springframework.web.bind.annotation.RestController;
16 |
17 | import com.masai.model.Customer;
18 | import com.masai.service.CustomerService;
19 |
20 | import jakarta.websocket.server.PathParam;
21 |
22 | @RestController
23 | public class CustomerController {
24 |
25 | @Autowired
26 | private CustomerService customerService;
27 |
28 | @Autowired
29 | private PasswordEncoder passwordEncoder;
30 |
31 | @GetMapping("/hello")
32 | public String testHandler() {
33 | return "Welcome to Spring Security";
34 | }
35 |
36 | @PostMapping("/customers")
37 | public ResponseEntity saveCustomerHandler(@RequestBody Customer customer) {
38 |
39 | customer.setPassword(passwordEncoder.encode(customer.getPassword()));
40 |
41 | Customer registeredCustomer = customerService.registerCustomer(customer);
42 |
43 | return new ResponseEntity<>(registeredCustomer, HttpStatus.ACCEPTED);
44 |
45 | }
46 |
47 | @GetMapping("/customers/{email}")
48 | public ResponseEntity getCustomerByEmailHandler(@PathVariable("email") String email) {
49 |
50 | Customer customer = customerService.getCustomerDetailsByEmail(email);
51 |
52 | return new ResponseEntity<>(customer, HttpStatus.ACCEPTED);
53 |
54 | }
55 |
56 | @GetMapping("/customers")
57 | public ResponseEntity> getAllCustomerHandler() {
58 |
59 | List customers = customerService.getAllCustomerDetails();
60 |
61 | return new ResponseEntity<>(customers, HttpStatus.ACCEPTED);
62 |
63 | }
64 |
65 | }
66 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT2/SpringSecurityWithoutJwt/src/main/java/com/masai/controller/LoginController.java:
--------------------------------------------------------------------------------
1 | package com.masai.controller;
2 |
3 | import org.springframework.beans.factory.annotation.Autowired;
4 | import org.springframework.http.HttpStatus;
5 | import org.springframework.http.ResponseEntity;
6 | import org.springframework.security.authentication.BadCredentialsException;
7 | import org.springframework.security.core.Authentication;
8 | import org.springframework.web.bind.annotation.GetMapping;
9 | import org.springframework.web.bind.annotation.RestController;
10 |
11 | import com.masai.model.Customer;
12 | import com.masai.repository.CustomerRepository;
13 |
14 | @RestController
15 | public class LoginController {
16 |
17 | @Autowired
18 | private CustomerRepository customerRepository;
19 |
20 | @GetMapping("/signIn")
21 | public ResponseEntity getLoggedInCustomerDetailsHandler(Authentication auth){
22 |
23 |
24 | Customer customer= customerRepository.findByEmail(auth.getName()).orElseThrow(() -> new BadCredentialsException("Invalid Username or password"));
25 |
26 | return new ResponseEntity<>(customer, HttpStatus.ACCEPTED);
27 |
28 |
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT2/SpringSecurityWithoutJwt/src/main/java/com/masai/exception/CustomerException.java:
--------------------------------------------------------------------------------
1 | package com.masai.exception;
2 |
3 | public class CustomerException extends RuntimeException {
4 |
5 | public CustomerException() {
6 | // TODO Auto-generated constructor stub
7 | }
8 |
9 | public CustomerException(String message) {
10 | super(message);
11 | }
12 |
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT2/SpringSecurityWithoutJwt/src/main/java/com/masai/exception/GlobalExceptionHandler.java:
--------------------------------------------------------------------------------
1 | package com.masai.exception;
2 |
3 | import java.time.LocalDateTime;
4 |
5 | import org.springframework.http.HttpStatus;
6 | import org.springframework.http.ResponseEntity;
7 | import org.springframework.web.bind.annotation.ControllerAdvice;
8 | import org.springframework.web.bind.annotation.ExceptionHandler;
9 | import org.springframework.web.context.request.WebRequest;
10 |
11 | @ControllerAdvice
12 | public class GlobalExceptionHandler {
13 |
14 |
15 |
16 |
17 |
18 | @ExceptionHandler(CustomerException.class)
19 | public ResponseEntity customerExceptionHandler(CustomerException ce, WebRequest req){
20 |
21 |
22 | MyErrorDetails err= new MyErrorDetails();
23 | err.setTimestamp(LocalDateTime.now());
24 | err.setMessage(ce.getMessage());
25 | err.setDetails(req.getDescription(false));
26 |
27 | return new ResponseEntity(err, HttpStatus.BAD_REQUEST);
28 |
29 | }
30 |
31 |
32 |
33 | @ExceptionHandler(Exception.class)
34 | public ResponseEntity otherExceptionHandler(Exception se, WebRequest req){
35 |
36 |
37 | MyErrorDetails err= new MyErrorDetails();
38 | err.setTimestamp(LocalDateTime.now());
39 | err.setMessage(se.getMessage());
40 | err.setDetails(req.getDescription(false));
41 |
42 | return new ResponseEntity(err, HttpStatus.INTERNAL_SERVER_ERROR);
43 |
44 | }
45 |
46 |
47 |
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT2/SpringSecurityWithoutJwt/src/main/java/com/masai/exception/MyErrorDetails.java:
--------------------------------------------------------------------------------
1 | package com.masai.exception;
2 |
3 | import java.time.LocalDateTime;
4 |
5 | public class MyErrorDetails {
6 |
7 | private LocalDateTime timestamp;
8 | private String message;
9 | private String details;
10 |
11 |
12 | public MyErrorDetails() {
13 | // TODO Auto-generated constructor stub
14 | }
15 |
16 |
17 | public MyErrorDetails(LocalDateTime timestamp, String message, String details) {
18 | super();
19 | this.timestamp = timestamp;
20 | this.message = message;
21 | this.details = details;
22 | }
23 |
24 |
25 | public LocalDateTime getTimestamp() {
26 | return timestamp;
27 | }
28 |
29 |
30 | public void setTimestamp(LocalDateTime timestamp) {
31 | this.timestamp = timestamp;
32 | }
33 |
34 |
35 | public String getMessage() {
36 | return message;
37 | }
38 |
39 |
40 | public void setMessage(String message) {
41 | this.message = message;
42 | }
43 |
44 |
45 | public String getDetails() {
46 | return details;
47 | }
48 |
49 |
50 | public void setDetails(String details) {
51 | this.details = details;
52 | }
53 |
54 |
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT2/SpringSecurityWithoutJwt/src/main/java/com/masai/model/Customer.java:
--------------------------------------------------------------------------------
1 | package com.masai.model;
2 |
3 | import com.fasterxml.jackson.annotation.JsonProperty;
4 |
5 | import jakarta.persistence.Column;
6 | import jakarta.persistence.Entity;
7 | import jakarta.persistence.GeneratedValue;
8 | import jakarta.persistence.GenerationType;
9 | import jakarta.persistence.Id;
10 | import jakarta.persistence.UniqueConstraint;
11 | import lombok.Data;
12 |
13 | @Entity
14 | @Data
15 | public class Customer {
16 |
17 | @Id
18 | @GeneratedValue(strategy = GenerationType.AUTO)
19 | private Integer custId;
20 | private String name;
21 |
22 | @Column(unique = true)
23 | private String email;
24 | @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
25 | private String password;
26 | private String address;
27 |
28 |
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT2/SpringSecurityWithoutJwt/src/main/java/com/masai/repository/CustomerRepository.java:
--------------------------------------------------------------------------------
1 | package com.masai.repository;
2 |
3 | import java.util.Optional;
4 |
5 | import org.springframework.data.jpa.repository.JpaRepository;
6 |
7 | import com.masai.model.Customer;
8 |
9 | public interface CustomerRepository extends JpaRepository{
10 |
11 |
12 | public Optional findByEmail(String email);
13 | }
14 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT2/SpringSecurityWithoutJwt/src/main/java/com/masai/service/CustomerService.java:
--------------------------------------------------------------------------------
1 | package com.masai.service;
2 | import java.util.List;
3 |
4 | import com.masai.exception.CustomerException;
5 | import com.masai.model.Customer;
6 |
7 | public interface CustomerService {
8 |
9 | public Customer registerCustomer(Customer customer);
10 |
11 | public Customer getCustomerDetailsByEmail(String email)throws CustomerException;
12 |
13 | public List getAllCustomerDetails()throws CustomerException;
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT2/SpringSecurityWithoutJwt/src/main/java/com/masai/service/CustomerServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.masai.service;
2 |
3 | import java.util.List;
4 |
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.stereotype.Service;
7 |
8 | import com.masai.exception.CustomerException;
9 | import com.masai.model.Customer;
10 | import com.masai.repository.CustomerRepository;
11 |
12 | @Service
13 | public class CustomerServiceImpl implements CustomerService{
14 |
15 | @Autowired
16 | private CustomerRepository customerRepository;
17 |
18 | @Override
19 | public Customer registerCustomer(Customer customer) throws CustomerException {
20 |
21 | return customerRepository.save(customer);
22 |
23 |
24 | }
25 |
26 | @Override
27 | public Customer getCustomerDetailsByEmail(String email)throws CustomerException {
28 |
29 | return customerRepository.findByEmail(email).orElseThrow(() -> new CustomerException("Customer Not found with Email: "+email));
30 | }
31 |
32 | @Override
33 | public List getAllCustomerDetails()throws CustomerException {
34 |
35 | List customers= customerRepository.findAll();
36 |
37 | if(customers.isEmpty())
38 | throw new CustomerException("No Customer find");
39 |
40 | return customers;
41 |
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT2/SpringSecurityWithoutJwt/src/main/java/com/masai/service/CustomerUserDetailsService.java:
--------------------------------------------------------------------------------
1 | package com.masai.service;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Optional;
6 |
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.security.authentication.BadCredentialsException;
9 | import org.springframework.security.core.GrantedAuthority;
10 | import org.springframework.security.core.userdetails.User;
11 | import org.springframework.security.core.userdetails.UserDetails;
12 | import org.springframework.security.core.userdetails.UserDetailsService;
13 | import org.springframework.security.core.userdetails.UsernameNotFoundException;
14 | import org.springframework.stereotype.Service;
15 |
16 | import com.masai.model.Customer;
17 | import com.masai.repository.CustomerRepository;
18 |
19 | @Service
20 | public class CustomerUserDetailsService implements UserDetailsService{
21 |
22 | @Autowired
23 | private CustomerRepository customerRepository;
24 |
25 |
26 | @Override
27 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
28 |
29 |
30 | Optional opt= customerRepository.findByEmail(username);
31 |
32 | if(opt.isPresent()) {
33 |
34 | Customer customer= opt.get();
35 |
36 | List authorities= new ArrayList<>();
37 | //authorities.add(new SimpleGrantedAuthority(customer.getRole()));
38 |
39 |
40 | return new User(customer.getEmail(), customer.getPassword(), authorities);
41 |
42 |
43 |
44 | }else
45 | throw new BadCredentialsException("User Details not found with this username: "+username);
46 |
47 |
48 |
49 |
50 |
51 | }
52 |
53 | }
54 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT2/SpringSecurityWithoutJwt/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 |
2 | #db specific properties
3 | spring.datasource.url=jdbc:mysql://localhost:3306/prace
4 | spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
5 | spring.datasource.username=root
6 | spring.datasource.password=root
7 |
8 | #ORM s/w specific properties
9 | spring.jpa.hibernate.ddl-auto=update
10 | spring.jpa.show-sql=true
11 |
12 | #spring.security.user.name=ratan
13 | #spring.security.user.password=123
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/Spring_Security_Without_JWT2/SpringSecurityWithoutJwt/src/test/java/com/masai/SpringSecurityWithoutJwtApplicationTests.java:
--------------------------------------------------------------------------------
1 | package com.masai;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.springframework.boot.test.context.SpringBootTest;
5 |
6 | @SpringBootTest
7 | class SpringSecurityWithoutJwtApplicationTests {
8 |
9 | @Test
10 | void contextLoads() {
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/spring_security_live_session/SpringBoot_filters.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Shubh2-0/Spring_Security/a0d45807af1cd2b3f178a105f9b61b8bfaa7c8b6/spring_security_live_session/SpringBoot_filters.jpg
--------------------------------------------------------------------------------
/spring_security_live_session/SpringSecurity_session notes.txt:
--------------------------------------------------------------------------------
1 | 10:57 pm
2 |
3 | --there is a filter called "UsernamePasswordAuthernticationFilter" which will extract the username and password from the user request and build the "Authentication" object.
4 |
5 | --here Authentication is an interface and its implementation class name is "UsernamePasswordAuthenticationToken".
6 |
7 | --after creating the object of Authentication, this filter will call a method of AuthenticationManager(I)
8 | called:
9 |
10 | Authentication authenticate(Authentication auth);
11 |
12 | --here AuthenticationManager is an interface and the implementation class name is "ProviderManager"
13 |
14 | --this authenticate(-) method will check with variaous supported AuthenticationProviders and then this authenticate(-) method will call another
15 |
16 | Authentication authenticate(Authentication auth);
17 | method on the implementation of appropriate AuthenticationProvider.
18 |
19 | --the default implementation of AuthenticationProvider is DAOAuthenticationProvider.
20 |
21 | Note: we can define our own AuthenticationProvider implementation also.
22 |
23 |
24 | --this Default DAOAuthenticationProvider will take the help of UserDetailsService.
25 |
26 | --inside the UserDetailsService interface, there is only one abstract method called:
27 |
28 | UserDetails loadUserByUsername(String username);
29 |
30 | --we can implement this interface and return the UserDetails object based on our requirement.
31 |
32 | --By default Spring Security f/w has provided an implementation class of this UserDetailService interface
33 | which is "InMemoryUserDetailsService"
34 |
35 | Spring Security has provided the implementation of UserDetails interface also, the name of this implementation class is "User"
36 |
37 | --developer can implement this UserDetails interface and customize this User details object also.
38 |
39 |
40 | --Once AuthenticationManager will get the Authentication object after sucessfull authentication then AM will populate the Principle object inside this Authentication object and keep this Authentication object inside the SecurityContext object.
41 |
42 | Principle object will represent the Authenticated User.
43 |
44 |
45 |
46 | BasicAuthenticationFilter:
47 | --------------------------------
48 |
49 | this filter is responsible for processing any request that has a HTTP request header of Authorization with an authentication scheme of Basic and a Base64-encoded username:password token. For example, to authenticate user "bob" with password "1234" the following header would be presented:
50 |
51 | Authorization: Basic QWxhZGRpbjpvcGVuIHNlJHSKJJD
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
--------------------------------------------------------------------------------
/spring_security_live_session/spring_security_architecture.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Shubh2-0/Spring_Security/a0d45807af1cd2b3f178a105f9b61b8bfaa7c8b6/spring_security_live_session/spring_security_architecture.jpg
--------------------------------------------------------------------------------