Commit 29b6bad2 authored by Potharaju Peddi's avatar Potharaju Peddi

for spring security database

parents
# Default ignored files
/shelf/
/workspace.xml
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<ScalaCodeStyleSettings>
<option name="MULTILINE_STRING_CLOSING_QUOTES_ON_NEW_LINE" value="true" />
</ScalaCodeStyleSettings>
</code_scheme>
</component>
\ No newline at end of file
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="PREFERRED_PROJECT_CODE_STYLE" value="Default" />
</state>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<annotationProcessing>
<profile default="true" name="Default" enabled="true" />
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="spring-security-latest" />
</profile>
</annotationProcessing>
<bytecodeTargetLevel target="17" />
</component>
<component name="JavacSettings">
<option name="ADDITIONAL_OPTIONS_OVERRIDE">
<module name="spring-security-latest" options="-parameters" />
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="spring-milestones" />
<option name="name" value="Spring Milestones" />
<option name="url" value="https://artifactory.albertsons.com/artifactory/SafewayPublicGroup/" />
</remote-repository>
<remote-repository>
<option name="id" value="repository.jfrog.deployment.development" />
<option name="name" value="libs-release-local" />
<option name="url" value="https://artifactory.albertsons.com/artifactory/SafewayPublicGroup/" />
</remote-repository>
<remote-repository>
<option name="id" value="archetype" />
<option name="name" value="archetype" />
<option name="url" value="https://artifactory.albertsons.com/artifactory/SafewayPublicGroup/" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://artifactory.albertsons.com/artifactory/SafewayPublicGroup/" />
</remote-repository>
<remote-repository>
<option name="id" value="confluent" />
<option name="name" value="confluent" />
<option name="url" value="https://artifactory.albertsons.com/artifactory/SafewayPublicGroup/" />
</remote-repository>
<remote-repository>
<option name="id" value="repository.jfrog.deployment" />
<option name="name" value="Safeway JFrog Repository" />
<option name="url" value="https://artifactory.albertsons.com/artifactory/SafewayPublicGroup/" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
<remote-repository>
<option name="id" value="libsreleaselocal" />
<option name="name" value="libsreleaselocal" />
<option name="url" value="https://artifactory.albertsons.com/artifactory/SafewayPublicGroup/" />
</remote-repository>
<remote-repository>
<option name="id" value="SafewayPublicGroup" />
<option name="name" value="SafewayPublicGroup" />
<option name="url" value="https://artifactory.albertsons.com/artifactory/SafewayPublicGroup/" />
</remote-repository>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="17" project-jdk-type="JavaSDK" />
</project>
\ No newline at end of file
H
java:S2699
"-Add at least one assertion to this test case.(áùêÌùÿÿÿÿ
\ No newline at end of file
~
java:S6813"BRemove this field injection and use constructor injection instead.(êæÄÞJ$1c2cd0d3-1507-475b-bf97-151ccd277876
~
java:S6813"BRemove this field injection and use constructor injection instead.(êæÄÞJ$af6ec988-2f38-4af7-bbe5-b9ea04379dc2
_
java:S2119!"Save and re-use this "Random".(Ž¥ŒÌøÿÿÿÿJ$804b68f4-6cea-4937-b75d-25c751018256
_
java:S2119""Save and re-use this "Random".(«éö™ûÿÿÿÿJ$bacfa7f3-86e4-48e5-a648-f6a0105862cf
\ No newline at end of file
~
java:S6813"BRemove this field injection and use constructor injection instead.(êæÄÞJ$0b6b6c23-8b94-45c1-b86a-5cfba0a90cf8
\ No newline at end of file
~
java:S6813"BRemove this field injection and use constructor injection instead.(êæÄÞJ$142e0408-782c-4692-bcbc-2b2933956fe7
\ No newline at end of file
n
java:S2699
"-Add at least one assertion to this test case.(áùêÌùÿÿÿÿJ$72dc6a51-fb3a-4c84-8cda-a4b937230126
\ No newline at end of file

java:S1128"TRemove this unnecessary import: same package classes are always implicitly imported.(Ӧ8ﻉ2J$260648f3-0b6c-4097-a65c-660b538ff624

java:S1128"{Remove this unused import 'org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity'.(Ԑ8ﻉ2J$71321a30-9b1e-44e5-b3bc-00545702f4c7

java:S1128 "ORemove this unused import 'org.springframework.security.core.userdetails.User'.(Ā8ﻉ2J$5c74dd10-cac4-402e-a8f5-dc8ccd8efeff

java:S1128 "VRemove this unused import 'org.springframework.security.core.userdetails.UserDetails'.(ʁ8ﻉ2J$e3c03899-986e-4ba8-a1ed-6d82397b3ed2

java:S1128"aRemove this unused import 'org.springframework.security.provisioning.InMemoryUserDetailsManager'.(8ﻉ2J$5167a890-1f60-46df-9e51-5be49e97c09b
\ No newline at end of file
9
README.md,8\e\8ec9a00bfd09b3190ac6b22251dbb1aa95a0579d
m
=src/main/java/com/security/repository/UserInfoRepository.java,e\c\ec6f1a4921102e091b5376eb4c12e21bf3948af8
_
/src/main/java/com/security/entity/UserInfo.java,5\b\5ba460316b38b121484d9b74b9a7d8eab5f372a4
e
5src/main/java/com/security/config/SecurityConfig.java,e\c\ecc1f75d634e44e274961aec1bbc6bc47d4a9130
j
:src/main/java/com/security/config/UserInfoUserDetails.java,6\2\62f9f22b9dc027ef5e1c6b93742d070fca70b7e1
q
Asrc/main/java/com/security/config/UserInfoUserDetailsService.java,5\4\54e00d613a72644aad1feb4cf80566fed8cf6dbd
l
<src/main/java/com/security/controller/ProductController.java,b\e\be6944e238152a9b6f8d7fda0d82cdd5e84e2705
[
+src/main/java/com/security/dto/Product.java,7\4\74c01e88c7758bc641b292deddd00a9778301bfd
t
Dsrc/test/java/com/security/SpringSecurityLatestApplicationTests.java,2\d\2d28391a986a41e212e94a0648f167c157cc307a
o
?src/main/java/com/security/SpringSecurityLatestApplication.java,5\9\596886e7bf3d537b416ccfcffdfce3d5642d8558
v
Fsrc/test/java/com/javatechie/SpringSecurityLatestApplicationTests.java,d\d\dd4cb18f05730d3c43337ceeb482cfa38e3a3e85
f
6src/main/java/com/security/service/ProductService.java,3\7\37aef645278cb9a72a0d67ae86f2f237d99342d9
\ No newline at end of file
9
README.md,8\e\8ec9a00bfd09b3190ac6b22251dbb1aa95a0579d
m
=src/main/java/com/security/repository/UserInfoRepository.java,e\c\ec6f1a4921102e091b5376eb4c12e21bf3948af8
_
/src/main/java/com/security/entity/UserInfo.java,5\b\5ba460316b38b121484d9b74b9a7d8eab5f372a4
e
5src/main/java/com/security/config/SecurityConfig.java,e\c\ecc1f75d634e44e274961aec1bbc6bc47d4a9130
j
:src/main/java/com/security/config/UserInfoUserDetails.java,6\2\62f9f22b9dc027ef5e1c6b93742d070fca70b7e1
q
Asrc/main/java/com/security/config/UserInfoUserDetailsService.java,5\4\54e00d613a72644aad1feb4cf80566fed8cf6dbd
l
<src/main/java/com/security/controller/ProductController.java,b\e\be6944e238152a9b6f8d7fda0d82cdd5e84e2705
[
+src/main/java/com/security/dto/Product.java,7\4\74c01e88c7758bc641b292deddd00a9778301bfd
t
Dsrc/test/java/com/security/SpringSecurityLatestApplicationTests.java,2\d\2d28391a986a41e212e94a0648f167c157cc307a
o
?src/main/java/com/security/SpringSecurityLatestApplication.java,5\9\596886e7bf3d537b416ccfcffdfce3d5642d8558
v
Fsrc/test/java/com/javatechie/SpringSecurityLatestApplicationTests.java,d\d\dd4cb18f05730d3c43337ceeb482cfa38e3a3e85
f
6src/main/java/com/security/service/ProductService.java,3\7\37aef645278cb9a72a0d67ae86f2f237d99342d9
\ No newline at end of file
# spring-boot-security-3.0
Note : If you are using spring boot 3.1.x version then please do the below code change
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(auth ->
auth.requestMatchers("/product-service/welcome", "/product-service/addNewUser").permitAll()
.requestMatchers("/product-service/**")
.authenticated()
)
.httpBasic(Customizer.withDefaults()).build();
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.security</groupId>
<artifactId>spring-security-latest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-security-latest</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.security;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringSecurityLatestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringSecurityLatestApplication.class, args);
}
}
package com.security.config;
import com.security.config.UserInfoUserDetailsService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
@Bean
//authentication
public UserDetailsService userDetailsService() {
return new UserInfoUserDetailsService();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http.csrf().disable()
.authorizeHttpRequests()
.requestMatchers("/products/welcome","/products/new").permitAll()
.and()
.authorizeHttpRequests().requestMatchers("/products/**")
.authenticated().and().formLogin().and().build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationProvider authenticationProvider(){
DaoAuthenticationProvider authenticationProvider=new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService());
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
}
}
package com.security.config;
import com.security.entity.UserInfo;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
public class UserInfoUserDetails implements UserDetails {
private String name;
private String password;
private List<GrantedAuthority> authorities;
public UserInfoUserDetails(UserInfo userInfo) {
name=userInfo.getName();
password=userInfo.getPassword();
authorities= Arrays.stream(userInfo.getRoles().split(","))
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return name;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
package com.security.config;
import com.security.entity.UserInfo;
import com.security.repository.UserInfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import java.util.Optional;
@Component
public class UserInfoUserDetailsService implements UserDetailsService {
@Autowired
private UserInfoRepository repository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional<UserInfo> userInfo = repository.findByName(username);
return userInfo.map(UserInfoUserDetails::new)
.orElseThrow(() -> new UsernameNotFoundException("user not found " + username));
}
}
package com.security.controller;
import com.security.dto.Product;
import com.security.entity.UserInfo;
import com.security.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/products")
public class ProductController {
@Autowired
private ProductService service;
@GetMapping("/welcome")
public String welcome() {
return "Welcome this endpoint is not secure";
}
@PostMapping("/new")
public String addNewUser(@RequestBody UserInfo userInfo){
return service.addUser(userInfo);
}
@GetMapping("/all")
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
public List<Product> getAllTheProducts() {
return service.getProducts();
}
@GetMapping("/{id}")
@PreAuthorize("hasAuthority('ROLE_USER')")
public Product getProductById(@PathVariable int id) {
return service.getProduct(id);
}
}
package com.security.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Product {
private int productId;
private String name;
private int qty;
private double price;
}
package com.security.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserInfo {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String email;
private String password;
private String roles;
}
package com.security.repository;
import com.security.entity.UserInfo;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface UserInfoRepository extends JpaRepository<UserInfo, Integer> {
Optional<UserInfo> findByName(String username);
}
package com.security.service;
import com.security.dto.Product;
import com.security.entity.UserInfo;
import com.security.repository.UserInfoRepository;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
@Service
public class ProductService {
List<Product> productList = null;
@Autowired
private UserInfoRepository repository;
@Autowired
private PasswordEncoder passwordEncoder;
@PostConstruct
public void loadProductsFromDB() {
productList = IntStream.rangeClosed(1, 100)
.mapToObj(i -> Product.builder()
.productId(i)
.name("product " + i)
.qty(new Random().nextInt(10))
.price(new Random().nextInt(5000)).build()
).collect(Collectors.toList());
}
public List<Product> getProducts() {
return productList;
}
public Product getProduct(int id) {
return productList.stream()
.filter(product -> product.getProductId() == id)
.findAny()
.orElseThrow(() -> new RuntimeException("product " + id + " not found"));
}
public String addUser(UserInfo userInfo) {
userInfo.setPassword(passwordEncoder.encode(userInfo.getPassword()));
repository.save(userInfo);
return "user added to system ";
}
}
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/springsecurity
spring.datasource.username = root
spring.datasource.password = Puneeth@27
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
package com.javatechie;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringSecurityLatestApplicationTests {
@Test
void contextLoads() {
}
}
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/springsecurity
spring.datasource.username = root
spring.datasource.password = Puneeth@27
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment