Commit 5f2c02db authored by Potharaju Peddi's avatar Potharaju Peddi

for spring security JWT

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 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>
</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="corretto-17" project-jdk-type="JavaSDK" />
</project>
\ No newline at end of file
M
java:S1128"7Remove this unused import 'io.jsonwebtoken.io.Decoder'.(ʱ
\ No newline at end of file
X
java:S6813"BRemove this field injection and use constructor injection instead.(êæÄÞ
\ No newline at end of file
…
java:S6813"BRemove this field injection and use constructor injection instead.(êæÄÞ8©Žšç‰2J$1c44d02e-486b-4552-b154-b7577de5f12d
…
java:S6813"BRemove this field injection and use constructor injection instead.(êæÄÞ8©Žšç‰2J$51399626-ed62-42c4-aa2a-25cc6323fa87
…
java:S6813"BRemove this field injection and use constructor injection instead.(êæÄÞ8©Žšç‰2J$a7f47e2e-3e83-49a9-a7fe-ebf252bf8aea
ƒ java:S1259"<This block of commented-out lines of code should be removed.(ÆÄÑãûÿÿÿÿ8®Žšç‰2J$40a7e004-15a7-4234-bd14-33f4003687bf
~ java:S125<"<This block of commented-out lines of code should be removed.(¡Õ±š8®Žšç‰2J$b0b3a4e9-0d82-4a22-91f8-3da14f9d6756
\ No newline at end of file
7
java:S1220""Move this file to a named package.8ijçç‰2
] java:S125"<This block of commented-out lines of code should be removed.(Ò·Äøÿÿÿÿ8ųçç‰2
\ No newline at end of file
X java:S125"<This block of commented-out lines of code should be removed.(Í´åù8ÐÆìç‰2
~ java:S125"<This block of commented-out lines of code should be removed.(ØÄ²¼8ôÞëç‰2J$de1f2d04-5539-4b29-ad35-218fb854ee1b
ƒ java:S125/"<This block of commented-out lines of code should be removed.(™†úÿÿÿÿ8Ýêäç‰2J$ae13857a-39bf-472c-91e8-b19a62ddb171
} java:S125@"<This block of commented-out lines of code should be removed.(¢ÍU8ßêäç‰2J$b2394fc7-6023-42a7-a6da-2d22d5cbd611
\ No newline at end of file
9
README.md,8\e\8ec9a00bfd09b3190ac6b22251dbb1aa95a0579d
d
4src/main/java/com/javatechie/service/JwtService.java,2\9\29f322e65e1a57847fe5afe739adf0b81e1278d7
b
2src/main/java/com/security/service/JwtService.java,8\b\8b7c3fed9e2db7675e48ffc65115c10a9862b625
o
?src/main/java/com/security/SpringSecurityLatestApplication.java,5\9\596886e7bf3d537b416ccfcffdfce3d5642d8558
m
=src/main/java/com/security/repository/UserInfoRepository.java,e\c\ec6f1a4921102e091b5376eb4c12e21bf3948af8
d
4src/main/java/com/security/filter/JwtAuthFilter.java,b\f\bfe29da8718f213f934e76aa7abdf9289f146f9d
_
/src/main/java/com/security/entity/UserInfo.java,5\b\5ba460316b38b121484d9b74b9a7d8eab5f372a4
l
<src/main/java/com/security/controller/ProductController.java,b\e\be6944e238152a9b6f8d7fda0d82cdd5e84e2705
e
5src/main/java/com/security/config/SecurityConfig.java,e\c\ecc1f75d634e44e274961aec1bbc6bc47d4a9130
q
Asrc/main/java/com/security/config/UserInfoUserDetailsService.java,5\4\54e00d613a72644aad1feb4cf80566fed8cf6dbd
\ No newline at end of file
9
README.md,8\e\8ec9a00bfd09b3190ac6b22251dbb1aa95a0579d
d
4src/main/java/com/javatechie/service/JwtService.java,2\9\29f322e65e1a57847fe5afe739adf0b81e1278d7
b
2src/main/java/com/security/service/JwtService.java,8\b\8b7c3fed9e2db7675e48ffc65115c10a9862b625
o
?src/main/java/com/security/SpringSecurityLatestApplication.java,5\9\596886e7bf3d537b416ccfcffdfce3d5642d8558
m
=src/main/java/com/security/repository/UserInfoRepository.java,e\c\ec6f1a4921102e091b5376eb4c12e21bf3948af8
d
4src/main/java/com/security/filter/JwtAuthFilter.java,b\f\bfe29da8718f213f934e76aa7abdf9289f146f9d
_
/src/main/java/com/security/entity/UserInfo.java,5\b\5ba460316b38b121484d9b74b9a7d8eab5f372a4
l
<src/main/java/com/security/controller/ProductController.java,b\e\be6944e238152a9b6f8d7fda0d82cdd5e84e2705
e
5src/main/java/com/security/config/SecurityConfig.java,e\c\ecc1f75d634e44e274961aec1bbc6bc47d4a9130
q
Asrc/main/java/com/security/config/UserInfoUserDetailsService.java,5\4\54e00d613a72644aad1feb4cf80566fed8cf6dbd
\ No newline at end of file
# spring-boot3-jwt
\ No newline at end of file
<?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.javatechie</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>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
</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.filter.JwtAuthFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
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.config.http.SessionCreationPolicy;
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.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
// @Autowired
// private JwtAuthFilter authFilter;
@Bean
//authentication
public UserDetailsService userDetailsService() {
return new UserInfoUserDetailsService();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http.csrf().disable()
.authorizeHttpRequests()
.requestMatchers("/products/new","/products/authenticate").permitAll()
.and()
.authorizeHttpRequests().requestMatchers("/products/**")
.authenticated().and().formLogin().and().build();
// .sessionManagement()
// .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
// .and()
// .authenticationProvider(authenticationProvider())
// .addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class)
// .build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationProvider authenticationProvider(){
DaoAuthenticationProvider authenticationProvider=new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService());
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
}
// to enable db check
// @Bean
// public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
// return config.getAuthenticationManager();
// }
}
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.AuthRequest;
import com.security.dto.Product;
import com.security.entity.UserInfo;
import com.security.service.JwtService;
import com.security.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/products")
public class ProductController {
@Autowired
private ProductService service;
@Autowired
private JwtService jwtService;
@Autowired
private AuthenticationManager authenticationManager;
@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);
}
@PostMapping("/authenticate")
public String authenticateAndGetToken(@RequestBody AuthRequest authRequest) {
// to enable for authenticate DB
// Authentication authentication = authenticationManager.authenticate
// (new UsernamePasswordAuthenticationToken(authRequest.getUsername(), authRequest.getPassword()));
// if (authentication.isAuthenticated()) {
return jwtService.generateToken(authRequest.getUsername());
// } else {
// throw new UsernameNotFoundException("invalid user request !");
// }
}
}
package com.security.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AuthRequest {
private String username ;
private String password;
}
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.filter;
//
//import com.security.config.UserInfoUserDetailsService;
//import com.security.service.JwtService;
//import jakarta.servlet.FilterChain;
//import jakarta.servlet.ServletException;
//import jakarta.servlet.http.HttpServletRequest;
//import jakarta.servlet.http.HttpServletResponse;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
//import org.springframework.security.core.context.SecurityContextHolder;
//import org.springframework.security.core.userdetails.UserDetails;
//import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
//import org.springframework.stereotype.Component;
//import org.springframework.web.filter.OncePerRequestFilter;
//
//import java.io.IOException;
//
//@Component
//public class JwtAuthFilter extends OncePerRequestFilter {
//
// @Autowired
// private JwtService jwtService;
//
// @Autowired
// private UserInfoUserDetailsService userDetailsService;
//
// @Override
// protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
// String authHeader = request.getHeader("Authorization");
// String token = null;
// String username = null;
// if (authHeader != null && authHeader.startsWith("Bearer ")) {
// token = authHeader.substring(7);
// username = jwtService.extractUsername(token);
// }
//
// if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
// UserDetails userDetails = userDetailsService.loadUserByUsername(username);
// if (jwtService.validateToken(token, userDetails)) {
// UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
// authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
// SecurityContextHolder.getContext().setAuthentication(authToken);
// }
// }
// filterChain.doFilter(request, response);
// }
//}
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 io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
@Component
public class JwtService {
public static final String SECRET = "5367566B59703373367639792F423F4528482B4D6251655468576D5A71347437";
public String extractUsername(String token) {
return extractClaim(token, Claims::getSubject);
}
public Date extractExpiration(String token) {
return extractClaim(token, Claims::getExpiration);
}
public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
final Claims claims = extractAllClaims(token);
return claimsResolver.apply(claims);
}
private Claims extractAllClaims(String token) {
return Jwts
.parserBuilder()
.setSigningKey(getSignKey())
.build()
.parseClaimsJws(token)
.getBody();
}
private Boolean isTokenExpired(String token) {
return extractExpiration(token).before(new Date());
}
public Boolean validateToken(String token, UserDetails userDetails) {
final String username = extractUsername(token);
return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
}
public String generateToken(String userName){
Map<String,Object> claims=new HashMap<>();
return createToken(claims,userName);
}
private String createToken(Map<String, Object> claims, String userName) {
return Jwts.builder()
.setClaims(claims)
.setSubject(userName)
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis()+1000*60*30))
.signWith(getSignKey(), SignatureAlgorithm.HS256).compact();
}
private Key getSignKey() {
byte[] keyBytes= Decoders.BASE64.decode(SECRET);
return Keys.hmacShaKeyFor(keyBytes);
}
}
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 = Password
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.security;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringSecurityLatestApplicationTests {
@Test
void contextLoads() {
}
}
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