updated code mohd arham
This commit is contained in:
@@ -10,6 +10,7 @@ import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.billpaymentservice.bbps.entites.UserEntity;
|
||||
import com.billpaymentservice.bbps.entites.UsersDetails;
|
||||
import com.billpaymentservice.bbps.repository.UsersDetailsRepository;
|
||||
|
||||
@@ -22,13 +23,11 @@ public class CustomUserDetailsService implements UserDetailsService {
|
||||
@Override
|
||||
public UserDetails loadUserByUsername(String userMobNo) throws UsernameNotFoundException {
|
||||
|
||||
String normalizedEmail = userMobNo;
|
||||
|
||||
Optional<UsersDetails> adminOptional = userRepo.findByUserMobNo(normalizedEmail);
|
||||
Optional<UserEntity> adminOptional = userRepo.findByMobile(userMobNo);
|
||||
|
||||
if (adminOptional.isPresent()) {
|
||||
UsersDetails user = adminOptional.get();
|
||||
return new User(user.getUserEmailId(), user.getUserMobNo(), new ArrayList<>());
|
||||
UserEntity user = adminOptional.get();
|
||||
return new User(user.getMobile(), user.getName(), new ArrayList<>());
|
||||
} else {
|
||||
throw new UsernameNotFoundException("User not found with MobNo: " + userMobNo);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ package com.billpaymentservice.bbps.config;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
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;
|
||||
@@ -19,11 +18,14 @@ import jakarta.servlet.http.HttpServletResponse;
|
||||
@Component
|
||||
public class JwtFilter extends OncePerRequestFilter {
|
||||
|
||||
@Autowired
|
||||
private JwtUtil jwtUtil;
|
||||
private final JwtUtil jwtUtil;
|
||||
|
||||
@Autowired
|
||||
private CustomUserDetailsService userDetailsService;
|
||||
private final CustomUserDetailsService userDetailsService;
|
||||
|
||||
public JwtFilter(JwtUtil jwtUtil, CustomUserDetailsService userDetailsService) {
|
||||
this.jwtUtil = jwtUtil;
|
||||
this.userDetailsService = userDetailsService;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
@@ -31,13 +33,13 @@ public class JwtFilter extends OncePerRequestFilter {
|
||||
|
||||
final String authorizationHeader = request.getHeader("Authentication");
|
||||
|
||||
String email = null;
|
||||
String mobileNo = null;
|
||||
String jwt = null;
|
||||
|
||||
if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
|
||||
jwt = authorizationHeader.substring(7);
|
||||
try {
|
||||
email = jwtUtil.extractUsername(jwt);
|
||||
mobileNo = jwtUtil.extractUsername(jwt);
|
||||
} catch (IllegalArgumentException e) {
|
||||
System.out.println("unable to get jwt tokken");
|
||||
} catch (ExpiredJwtException e) {
|
||||
@@ -47,11 +49,10 @@ public class JwtFilter extends OncePerRequestFilter {
|
||||
}
|
||||
}
|
||||
|
||||
if (email != null && SecurityContextHolder.getContext().getAuthentication() == null) {
|
||||
if (mobileNo != null && SecurityContextHolder.getContext().getAuthentication() == null) {
|
||||
|
||||
UserDetails userDetails = this.userDetailsService.loadUserByUsername(email);
|
||||
UserDetails userDetails = this.userDetailsService.loadUserByUsername(mobileNo);
|
||||
|
||||
|
||||
if (jwtUtil.validateToken(jwt, userDetails)) {
|
||||
|
||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
|
||||
@@ -60,7 +61,7 @@ public class JwtFilter extends OncePerRequestFilter {
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
|
||||
} else {
|
||||
System.out.println("JWT Filter: Token validation failed for user - " + email);
|
||||
System.out.println("JWT Filter: Token validation failed for user - " + mobileNo);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,8 @@ import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.billpaymentservice.bbps.util.BBPSConstant;
|
||||
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
@@ -22,22 +24,23 @@ public class JwtUtil {
|
||||
@Value("${jwt.secret}")
|
||||
private String secret;
|
||||
|
||||
private final Map<String, Date> tokenBlacklist = new HashMap<>();
|
||||
|
||||
private Key getSigningKey() {
|
||||
byte[] keyBytes = Decoders.BASE64.decode(secret);
|
||||
return Keys.hmacShaKeyFor(keyBytes);
|
||||
}
|
||||
|
||||
// Access Token - 2 Hours
|
||||
private final long jwtExpirationInMs = 1000 * 60 * 60 * 2; // 2 hours
|
||||
|
||||
// Refresh Token - 7 Days
|
||||
private final long refreshExpirationDateInMs = 1000L * 60 * 60 * 24 * 7; // 7 days
|
||||
|
||||
private final Map<String, Date> tokenBlacklist = new HashMap<>();
|
||||
public String generateToken(String username, String mid) {
|
||||
Map<String, Object> claims = new HashMap<>();
|
||||
claims.put("mid", mid);
|
||||
claims.put("expiryTime", new Date(System.currentTimeMillis() + BBPSConstant.JWT_EXPIRATION_MS).toString());
|
||||
return createToken(claims, username.toUpperCase());
|
||||
}
|
||||
|
||||
public String doGenerateRefreshToken(Map<String, Object> claims, String subject) {
|
||||
return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
|
||||
.setExpiration(new Date(System.currentTimeMillis() + refreshExpirationDateInMs))
|
||||
.setExpiration(new Date(System.currentTimeMillis() + BBPSConstant.REFRESH_EXPIRATION_MS))
|
||||
.signWith(getSigningKey(), SignatureAlgorithm.HS512).compact();
|
||||
}
|
||||
|
||||
@@ -62,28 +65,28 @@ public class JwtUtil {
|
||||
return extractExpiration(token).before(new Date());
|
||||
}
|
||||
|
||||
public String generateToken(String username, String mid) {
|
||||
Map<String, Object> claims = new HashMap<>();
|
||||
claims.put("mid", mid);
|
||||
claims.put("expiryTime", new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10).toString());
|
||||
return createToken(claims, username.toUpperCase());
|
||||
private String createToken(Map<String, Object> claims, String subject) {
|
||||
return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
|
||||
.setExpiration(new Date(System.currentTimeMillis() + BBPSConstant.JWT_EXPIRATION_MS))
|
||||
.signWith(getSigningKey(), SignatureAlgorithm.HS512).compact();
|
||||
}
|
||||
|
||||
private String createToken(Map<String, Object> claims, String subject) {
|
||||
private String createToken1(Map<String, Object> claims,String subject) {
|
||||
return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
|
||||
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10))
|
||||
.signWith(getSigningKey(), SignatureAlgorithm.HS512).compact();
|
||||
}
|
||||
|
||||
private String createToken1(String subject) {
|
||||
return Jwts.builder().setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
|
||||
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10))
|
||||
.signWith(getSigningKey(), SignatureAlgorithm.HS512).compact();
|
||||
}
|
||||
// public Boolean validateToken(String token, UserDetails userDetails) {
|
||||
// final String username = extractUsername(token);
|
||||
// return true;
|
||||
// }
|
||||
|
||||
public Boolean validateToken(String token, UserDetails userDetails) {
|
||||
final String username = extractUsername(token);
|
||||
return true;
|
||||
final String mobileNo = extractUsername(token);
|
||||
// System.out.println("Extracted mobileNo from token: " + mobileNo );
|
||||
// System.out.println("Username from UserDetails: " + userDetails.getUsername());
|
||||
return (mobileNo .equals(userDetails.getUsername()) && !isTokenExpired(token));
|
||||
}
|
||||
|
||||
public void invalidateToken(String token) {
|
||||
@@ -96,7 +99,9 @@ public class JwtUtil {
|
||||
}
|
||||
|
||||
public String generateToken(String mobileNo) {
|
||||
return createToken1(mobileNo);
|
||||
Map<String, Object> claims = new HashMap<>();
|
||||
claims.put("mobileNo", mobileNo);
|
||||
return createToken1(claims,mobileNo);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -2,9 +2,7 @@ package com.billpaymentservice.bbps.config;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
@@ -20,11 +18,14 @@ import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
@EnableWebSecurity
|
||||
public class SecurityConfig {
|
||||
|
||||
@Autowired
|
||||
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
|
||||
private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
|
||||
|
||||
@Autowired
|
||||
private JwtFilter jwtFilter;
|
||||
private final JwtFilter jwtFilter;
|
||||
|
||||
public SecurityConfig(JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint, JwtFilter jwtFilter) {
|
||||
this.jwtAuthenticationEntryPoint = jwtAuthenticationEntryPoint;
|
||||
this.jwtFilter = jwtFilter;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
|
||||
@@ -32,13 +33,13 @@ public class SecurityConfig {
|
||||
http.csrf(csrf -> csrf.disable()).cors(cors -> cors.configurationSource(corsConfigurationSource()))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers("/auth/**",
|
||||
"/v3/api-docs/**",
|
||||
"/swagger-ui/**",
|
||||
"/swagger-ui.html",
|
||||
"/swagger-resources/**",
|
||||
"/webjars/**",
|
||||
"/error")
|
||||
.permitAll().requestMatchers(HttpMethod.OPTIONS, "/**").permitAll() // <-- Correct way
|
||||
"/v3/api-docs/**",
|
||||
"/swagger-ui/**",
|
||||
"/swagger-ui.html",
|
||||
"/swagger-resources/**",
|
||||
"/webjars/**",
|
||||
"/error")
|
||||
.permitAll().requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
|
||||
.anyRequest().authenticated())
|
||||
.exceptionHandling(ex -> ex.authenticationEntryPoint(jwtAuthenticationEntryPoint))
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
|
||||
|
||||
@@ -25,32 +25,32 @@ import lombok.extern.slf4j.Slf4j;
|
||||
@Slf4j
|
||||
public class AuthController {
|
||||
|
||||
private final AuthService authService;
|
||||
private final AuthService authService;
|
||||
|
||||
public AuthController(AuthService authService) {
|
||||
this.authService = authService;
|
||||
}
|
||||
public AuthController(AuthService authService) {
|
||||
this.authService = authService;
|
||||
}
|
||||
|
||||
@PostMapping(value = "/sendOtp", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public ResponseEntity<OtpSendResponse> sendOtp(@Validated @RequestBody LoginRequest request) {
|
||||
log.info("Received sendOtp request for mobile: {}", request.getMobile());
|
||||
OtpSendResponse resp = authService.sendOtp(request);
|
||||
return ResponseEntity.ok(resp);
|
||||
}
|
||||
@PostMapping(value = "/sendOtp", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public ResponseEntity<OtpSendResponse> sendOtp(@Validated @RequestBody LoginRequest request) {
|
||||
log.info("Received sendOtp request for mobile: {}", request.getMobile());
|
||||
OtpSendResponse resp = authService.sendOtp(request);
|
||||
return ResponseEntity.ok(resp);
|
||||
}
|
||||
|
||||
@PostMapping(value = "/verifyOtp", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public ResponseEntity<AuthResponses> verifyOtp(@Validated @RequestBody VerifyOtpRequest request) {
|
||||
AuthResponses resp = authService.verifyOtp(request);
|
||||
return ResponseEntity.ok(resp);
|
||||
}
|
||||
@PostMapping(value = "/verifyOtp", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public ResponseEntity<AuthResponses> verifyOtp(@Validated @RequestBody VerifyOtpRequest request) {
|
||||
AuthResponses resp = authService.verifyOtp(request);
|
||||
return ResponseEntity.ok(resp);
|
||||
}
|
||||
|
||||
@PostMapping(value = "/register", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public ResponseEntity<AuthResponse> register(@Validated @RequestBody RegisterRequest request) {
|
||||
AuthResponse resp = authService.registerUser(request);
|
||||
return ResponseEntity.ok(resp);
|
||||
}
|
||||
|
||||
@PostMapping("/loginWithoutDecryption")
|
||||
@PostMapping(value = "/register", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public ResponseEntity<AuthResponse> register(@Validated @RequestBody RegisterRequest request) {
|
||||
AuthResponse resp = authService.registerUser(request);
|
||||
return ResponseEntity.ok(resp);
|
||||
}
|
||||
|
||||
@PostMapping("/loginWithoutDecryption")
|
||||
public ResponseEntity<AuthResponses> login(@RequestBody LoginRequest loginRequest) {
|
||||
try {
|
||||
AuthResponses authResponse = authService.authenticateUser(loginRequest);
|
||||
@@ -60,5 +60,5 @@ public class AuthController {
|
||||
.message("An unexpected error occurred").statusCode(500).build());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -19,5 +19,5 @@ public class UserDetailsDTO {
|
||||
|
||||
private String userName;
|
||||
|
||||
private String userAge;
|
||||
private int userAge;
|
||||
}
|
||||
|
||||
@@ -5,11 +5,11 @@ import java.util.Optional;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.billpaymentservice.bbps.entites.UsersDetails;
|
||||
import com.billpaymentservice.bbps.entites.UserEntity;
|
||||
|
||||
@Repository
|
||||
public interface UsersDetailsRepository extends JpaRepository<UsersDetails, Long> {
|
||||
public interface UsersDetailsRepository extends JpaRepository<UserEntity, Long> {
|
||||
|
||||
Optional<UsersDetails> findByUserMobNo(String userMobNo);
|
||||
Optional<UserEntity> findByMobile(String userMobNo);
|
||||
|
||||
}
|
||||
|
||||
@@ -16,7 +16,6 @@ import com.billpaymentservice.bbps.dto.auth.UserDto;
|
||||
import com.billpaymentservice.bbps.dto.auth.VerifyOtpRequest;
|
||||
import com.billpaymentservice.bbps.dto.response.AuthResponses;
|
||||
import com.billpaymentservice.bbps.entites.UserEntity;
|
||||
import com.billpaymentservice.bbps.entites.UsersDetails;
|
||||
import com.billpaymentservice.bbps.repository.UserRepository;
|
||||
import com.billpaymentservice.bbps.repository.UsersDetailsRepository;
|
||||
import com.billpaymentservice.bbps.service.AuthService;
|
||||
@@ -37,14 +36,13 @@ public class AuthServiceImpl implements AuthService {
|
||||
|
||||
private final JwtUtil jwtUtil;
|
||||
|
||||
@Autowired
|
||||
public AuthServiceImpl(UserRepository userRepository, OtpClient otpClient, Helper helper,
|
||||
UsersDetailsRepository userRepo, JwtUtil jwtUtil) {
|
||||
this.userRepository = userRepository;
|
||||
this.otpClient = otpClient;
|
||||
this.helper = helper;
|
||||
this.userRepo=userRepo;
|
||||
this.jwtUtil=jwtUtil;
|
||||
this.userRepo = userRepo;
|
||||
this.jwtUtil = jwtUtil;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -63,28 +61,26 @@ public class AuthServiceImpl implements AuthService {
|
||||
@Override
|
||||
public AuthResponses verifyOtp(VerifyOtpRequest request) {
|
||||
boolean ok = otpClient.verifyOtp(request.getMobile(), request.getOtp());
|
||||
LOGGER.info("OTP STATUS"+ ok);
|
||||
LOGGER.info("OTP STATUS" + ok);
|
||||
if (ok) {
|
||||
return new AuthResponses("","Invalid OTP","Failed", 401, null);
|
||||
return new AuthResponses("", "Invalid OTP", "Failed", 401, null);
|
||||
}
|
||||
String mobileNo = request.getMobile();
|
||||
try {
|
||||
|
||||
|
||||
Optional<UsersDetails> byAdminEmail = userRepo.findByUserMobNo(mobileNo);
|
||||
Optional<UserEntity> byAdminEmail = userRepo.findByMobile(mobileNo);
|
||||
|
||||
if (byAdminEmail.isPresent()) {
|
||||
UsersDetails user = byAdminEmail.get();
|
||||
String token = jwtUtil.generateToken(user.getUserMobNo());
|
||||
UserEntity user = byAdminEmail.get();
|
||||
String token = jwtUtil.generateToken(user.getMobile());
|
||||
|
||||
LOGGER.info("Generated JWT token for mobileNo: " + mobileNo);
|
||||
|
||||
Object userDetailsDTO = null;
|
||||
|
||||
if (user != null) {
|
||||
userDetailsDTO = UserDetailsDTO.builder().id(user.getId()).userEmailId(user.getUserEmailId())
|
||||
.userMobNo(user.getUserMobNo()).userName(user.getUserName()).userAge(user.getUserAge())
|
||||
.build();
|
||||
userDetailsDTO = UserDetailsDTO.builder().id(user.getId()).userEmailId(user.getEmail())
|
||||
.userMobNo(user.getMobile()).userName(user.getName()).userAge(user.getAge()).build();
|
||||
}
|
||||
return new AuthResponses(token, "Success", "Login Done", 200, userDetailsDTO);
|
||||
} else {
|
||||
@@ -92,8 +88,8 @@ public class AuthServiceImpl implements AuthService {
|
||||
}
|
||||
|
||||
} catch (Exception ex) {
|
||||
System.out.println("Error occurred during login for mobile no: " + mobileNo
|
||||
+ " Exception: " + ex.getMessage());
|
||||
System.out.println(
|
||||
"Error occurred during login for mobile no: " + mobileNo + " Exception: " + ex.getMessage());
|
||||
|
||||
return AuthResponses.builder().status("Unauthorized").message("Authentication failed: " + ex.getMessage())
|
||||
.statusCode(401).build();
|
||||
@@ -137,20 +133,19 @@ public class AuthServiceImpl implements AuthService {
|
||||
try {
|
||||
String mobileNo = loginRequest.getMobile();
|
||||
|
||||
Optional<UsersDetails> byAdminEmail = userRepo.findByUserMobNo(mobileNo);
|
||||
Optional<UserEntity> byAdminEmail = userRepo.findByMobile(mobileNo);
|
||||
|
||||
if (byAdminEmail.isPresent()) {
|
||||
UsersDetails user = byAdminEmail.get();
|
||||
String token = jwtUtil.generateToken(user.getUserMobNo());
|
||||
UserEntity user = byAdminEmail.get();
|
||||
String token = jwtUtil.generateToken(user.getMobile());
|
||||
|
||||
LOGGER.info("Generated JWT token for mobileNo: " + mobileNo);
|
||||
|
||||
Object userDetailsDTO = null;
|
||||
|
||||
if (user != null) {
|
||||
userDetailsDTO = UserDetailsDTO.builder().id(user.getId()).userEmailId(user.getUserEmailId())
|
||||
.userMobNo(user.getUserMobNo()).userName(user.getUserName()).userAge(user.getUserAge())
|
||||
.build();
|
||||
userDetailsDTO = UserDetailsDTO.builder().id(user.getId()).userEmailId(user.getEmail())
|
||||
.userMobNo(user.getMobile()).userName(user.getName()).userAge(user.getAge()).build();
|
||||
}
|
||||
return new AuthResponses(token, "Success", "Login Done", 200, userDetailsDTO);
|
||||
} else {
|
||||
@@ -158,8 +153,8 @@ public class AuthServiceImpl implements AuthService {
|
||||
}
|
||||
|
||||
} catch (Exception ex) {
|
||||
System.out.println("Error occurred during login for mobile no: " + loginRequest.getMobile()
|
||||
+ " Exception: " + ex.getMessage());
|
||||
System.out.println("Error occurred during login for mobile no: " + loginRequest.getMobile() + " Exception: "
|
||||
+ ex.getMessage());
|
||||
|
||||
return AuthResponses.builder().status("Unauthorized").message("Authentication failed: " + ex.getMessage())
|
||||
.statusCode(401).build();
|
||||
|
||||
@@ -2,6 +2,10 @@ package com.billpaymentservice.bbps.util;
|
||||
|
||||
public class BBPSConstant {
|
||||
|
||||
// Jwt Token Expiration Time
|
||||
public static final long JWT_EXPIRATION_MS = 1000 * 60 * 60 * 24; // 24 hours
|
||||
public static final long REFRESH_EXPIRATION_MS = 1000L * 60 * 60 * 24 * 7; // 7 days
|
||||
|
||||
public static final Long SENT_TO_PROCESSOR_CODE = 198L;
|
||||
public static final Long SUCCESS_CODE = 200L;
|
||||
public static final Long FAILED_CODE = 99L;
|
||||
|
||||
Reference in New Issue
Block a user