Skip to content

Commit 0de93ee

Browse files
committed
Spring Boot Security, In Memory auth and end Points security is done.
1 parent add5ffd commit 0de93ee

File tree

6 files changed

+75
-2
lines changed

6 files changed

+75
-2
lines changed

pom.xml

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,10 @@
4848
<artifactId>modelmapper</artifactId>
4949
<version>3.1.0</version>
5050
</dependency>
51-
51+
<dependency>
52+
<groupId>org.springframework.boot</groupId>
53+
<artifactId>spring-boot-starter-security</artifactId>
54+
</dependency>
5255
<dependency>
5356
<groupId>org.springframework.boot</groupId>
5457
<artifactId>spring-boot-starter-test</artifactId>
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package com.manir.springbootecommercerestapi.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.method.configuration.EnableGlobalMethodSecurity;
7+
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
8+
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
9+
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
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.crypto.bcrypt.BCryptPasswordEncoder;
14+
import org.springframework.security.crypto.password.PasswordEncoder;
15+
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
16+
17+
@Configuration
18+
@EnableWebSecurity
19+
/***
20+
global security is used for enable security at method level for example permitting get methods
21+
Ex: PreAuthorize("hasRole('ADMIN')")
22+
***/
23+
@EnableGlobalMethodSecurity(prePostEnabled = true)
24+
public class SecurityConfig extends WebSecurityConfigurerAdapter {
25+
26+
@Override
27+
protected void configure(HttpSecurity http) throws Exception {
28+
http
29+
.csrf().disable()
30+
.authorizeRequests()
31+
//to permit all get request and secure post put and delete methods
32+
.antMatchers(HttpMethod.GET, "/api/**").permitAll()
33+
.anyRequest()
34+
.authenticated()
35+
.and()
36+
.httpBasic();
37+
38+
}
39+
40+
//In memory Auth
41+
@Override
42+
@Bean
43+
protected UserDetailsService userDetailsService() {
44+
UserDetails user = User.builder().username("user").password(passwordEncoder().encode("user")).roles("USER").build();
45+
UserDetails admin = User.builder().username("admin").password(passwordEncoder().encode("admin")).roles("ADMIN").build();
46+
47+
return new InMemoryUserDetailsManager(user, admin);
48+
}
49+
50+
@Bean
51+
PasswordEncoder passwordEncoder(){
52+
return new BCryptPasswordEncoder();
53+
}
54+
}

src/main/java/com/manir/springbootecommercerestapi/controller/CategoryController.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import org.springframework.beans.factory.annotation.Autowired;
88
import org.springframework.http.HttpStatus;
99
import org.springframework.http.ResponseEntity;
10+
import org.springframework.security.access.prepost.PreAuthorize;
1011
import org.springframework.web.bind.annotation.*;
1112

1213

@@ -18,6 +19,7 @@ public class CategoryController {
1819
private CategoryService categoryService;
1920

2021
//create category api
22+
@PreAuthorize("hasRole('ADMIN')")
2123
@PostMapping("/createCategory")
2224
public ResponseEntity<CategoryDto> createCategory(@RequestBody CategoryDto categoryDto){
2325
CategoryDto responseCategory = categoryService.createCategory(categoryDto);
@@ -42,6 +44,7 @@ public ResponseEntity<CategoryDto> getCatecoryById(@PathVariable Long categoryId
4244
}
4345

4446
//update category api
47+
@PreAuthorize("hasRole('ADMIN')")
4548
@PutMapping("/updateCategory/{categoryId}")
4649
public ResponseEntity<CategoryDto> updateCategory(@RequestBody CategoryDto categoryDto,
4750
@PathVariable Long categoryId){
@@ -50,6 +53,7 @@ public ResponseEntity<CategoryDto> updateCategory(@RequestBody CategoryDto categ
5053
}
5154

5255
//delete category api
56+
@PreAuthorize("hasRole('ADMIN')")
5357
@DeleteMapping("/deleteCategory/{categoryId}")
5458
public ResponseEntity<String> deleteCategory(@PathVariable Long categoryId){
5559
categoryService.deleteCategory(categoryId);

src/main/java/com/manir/springbootecommercerestapi/controller/ProductController.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import org.springframework.http.HttpStatus;
1010
import org.springframework.http.MediaType;
1111
import org.springframework.http.ResponseEntity;
12+
import org.springframework.security.access.prepost.PreAuthorize;
1213
import org.springframework.web.bind.annotation.*;
1314
import org.springframework.web.multipart.MultipartFile;
1415

@@ -22,6 +23,7 @@ public class ProductController {
2223
private ProductService productService;
2324

2425
//product create api
26+
@PreAuthorize("hasRole('ADMIN')")
2527
@RequestMapping(value = "/createProduct", method = RequestMethod.POST, consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE})
2628
public ResponseEntity<ProductDto> createProduct(@RequestPart("productDto") ProductDto productDto,
2729
@RequestPart("file") MultipartFile file){
@@ -30,6 +32,7 @@ public ResponseEntity<ProductDto> createProduct(@RequestPart("productDto") Produ
3032
}
3133

3234
//create product with category
35+
@PreAuthorize("hasRole('ADMIN')")
3336
@PostMapping("/{categoryId}/saveProductByCategoryId")
3437
public ResponseEntity<ProductDto> saveProductByCategoryId(@PathVariable Long categoryId,
3538
@RequestBody ProductDto productDto){
@@ -57,6 +60,7 @@ public ResponseEntity<ProductDto> getProductById(@PathVariable Long productId){
5760
}
5861

5962
//update product api
63+
@PreAuthorize("hasRole('ADMIN')")
6064
@PutMapping("/{categoryId}/updateProduct/{productId}")
6165
public ResponseEntity<ProductDto> updateProduct(@PathVariable Long categoryId,
6266
@RequestBody ProductDto productDto,
@@ -66,6 +70,7 @@ public ResponseEntity<ProductDto> updateProduct(@PathVariable Long categoryId,
6670
}
6771

6872
//delete product api
73+
@PreAuthorize("hasRole('ADMIN')")
6974
@DeleteMapping("/deleteProduct/{productId}")
7075
public ResponseEntity<String> deleteProduct(@PathVariable Long productId){
7176
productService.deleteProduct(productId);

src/main/java/com/manir/springbootecommercerestapi/service/Impl/ShoppingCartServiceImpl.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,4 +135,6 @@ private Product findProductById(Long productId){
135135
);
136136
return product;
137137
}
138+
139+
138140
}

src/main/resources/application.properties

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,10 @@ spring.datasource.username=root
66
spring.datasource.url=jdbc:mysql://localhost:3306/springBootEcommerceRestApi?serverTimezone=UTC
77
spring.jpa.hibernate.ddl-auto=update
88

9-
#logging.level.org.springframework.security=DEBUG
9+
#TO see security is working on the console
10+
logging.level.org.springframework.security=DEBUG
11+
#Spring security default auth credential
12+
#spring.security.user.password= user
13+
#spring.security.user.name= user
14+
#spring.security.user.roles= ADMIN
1015

0 commit comments

Comments
 (0)