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));
|
||||
|
||||
Reference in New Issue
Block a user