Implement refresh token functionality and enhance error handling in authentication
This commit is contained in:
@@ -1,7 +1,9 @@
|
||||
package com.jambotronGroup.jambotron.controllers;
|
||||
|
||||
|
||||
import com.jambotronGroup.jambotron.exceptions.TokenRefreshException;
|
||||
import com.jambotronGroup.jambotron.model.ERole;
|
||||
import com.jambotronGroup.jambotron.model.RefreshToken;
|
||||
import com.jambotronGroup.jambotron.model.Role;
|
||||
import com.jambotronGroup.jambotron.model.User;
|
||||
import com.jambotronGroup.jambotron.payload.request.LoginRequest;
|
||||
@@ -11,7 +13,9 @@ import com.jambotronGroup.jambotron.payload.response.UserInfoResponse;
|
||||
import com.jambotronGroup.jambotron.repository.RoleRepository;
|
||||
import com.jambotronGroup.jambotron.repository.UserRepository;
|
||||
import com.jambotronGroup.jambotron.security.jwt.JwtUtils;
|
||||
import com.jambotronGroup.jambotron.security.services.RefreshTokenService;
|
||||
import com.jambotronGroup.jambotron.security.services.UserDetailsImpl;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.validation.Valid;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -37,7 +41,7 @@ import java.util.stream.Collectors;
|
||||
@RequestMapping("/api/auth")
|
||||
public class AuthController {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(AuthController.class);
|
||||
private static final Logger _logger = LoggerFactory.getLogger(AuthController.class);
|
||||
@Autowired
|
||||
AuthenticationManager authenticationManager;
|
||||
|
||||
@@ -50,6 +54,9 @@ public class AuthController {
|
||||
@Autowired
|
||||
PasswordEncoder encoder;
|
||||
|
||||
@Autowired
|
||||
RefreshTokenService refreshTokenService;
|
||||
|
||||
@Autowired
|
||||
JwtUtils jwtUtils;
|
||||
|
||||
@@ -69,9 +76,16 @@ public class AuthController {
|
||||
.map(item -> item.getAuthority())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
logger.info("User {} authenticated successfully with roles: {}", userDetails.getUsername(), roles);
|
||||
RefreshToken refreshToken = refreshTokenService.createRefreshToken(userDetails.getId());
|
||||
|
||||
return ResponseEntity.ok().header(HttpHeaders.SET_COOKIE, jwtCookie.toString())
|
||||
ResponseCookie jwtRefreshCookie = jwtUtils.generateRefreshJwtCookie(refreshToken.getToken());
|
||||
|
||||
|
||||
_logger.info("User {} authenticated successfully with roles: {}", userDetails.getUsername(), roles);
|
||||
|
||||
return ResponseEntity.ok()
|
||||
.header(HttpHeaders.SET_COOKIE, jwtCookie.toString())
|
||||
.header(HttpHeaders.SET_COOKIE, jwtRefreshCookie.toString())
|
||||
.body(new UserInfoResponse(
|
||||
userDetails.getId(),
|
||||
userDetails.getUsername(),
|
||||
@@ -134,8 +148,42 @@ public class AuthController {
|
||||
|
||||
@PostMapping("/signout")
|
||||
public ResponseEntity<?> logoutUser() {
|
||||
Object principle = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
||||
if (principle.toString() != "anonymousUser") {
|
||||
Long userId = ((UserDetailsImpl) principle).getId();
|
||||
refreshTokenService.deleteByUserId(userId);
|
||||
}
|
||||
|
||||
ResponseCookie cookie = jwtUtils.getCleanJwtCookie();
|
||||
return ResponseEntity.ok().header(HttpHeaders.SET_COOKIE, cookie.toString())
|
||||
ResponseCookie jwtRefreshCookie = jwtUtils.getCleanJwtRefreshCookie();
|
||||
|
||||
_logger.info("User signed out successfully, cookies cleared.");
|
||||
return ResponseEntity.ok()
|
||||
.header(HttpHeaders.SET_COOKIE, cookie.toString())
|
||||
.header(HttpHeaders.SET_COOKIE, jwtRefreshCookie.toString())
|
||||
.body(new MessageResponse("You've been signed out!"));
|
||||
}
|
||||
|
||||
@PostMapping("/refreshtoken")
|
||||
public ResponseEntity<?> refreshtoken(HttpServletRequest request) {
|
||||
String refreshToken = jwtUtils.getJwtRefreshFromCookies(request);
|
||||
|
||||
if ((refreshToken != null) && (refreshToken.length() > 0)) {
|
||||
return refreshTokenService.findByToken(refreshToken)
|
||||
.map(refreshTokenService::verifyExpiration)
|
||||
.map(RefreshToken::getUser)
|
||||
.map(user -> {
|
||||
ResponseCookie jwtCookie = jwtUtils.generateJwtCookie(user);
|
||||
|
||||
_logger.info("Refresh token for user {} is valid, generating new JWT cookie.", user.getUsername());
|
||||
return ResponseEntity.ok()
|
||||
.header(HttpHeaders.SET_COOKIE, jwtCookie.toString())
|
||||
.body(new MessageResponse("Token is refreshed successfully!"));
|
||||
})
|
||||
.orElseThrow(() -> new TokenRefreshException(refreshToken,
|
||||
"Refresh token is not in database!"));
|
||||
}
|
||||
|
||||
return ResponseEntity.badRequest().body(new MessageResponse("Refresh Token is empty!"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.jambotronGroup.jambotron.exceptionHandlers;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public class ErrorMessage {
|
||||
private int statusCode;
|
||||
private Date timestamp;
|
||||
private String message;
|
||||
private String description;
|
||||
|
||||
public ErrorMessage(int statusCode, Date timestamp, String message, String description) {
|
||||
this.statusCode = statusCode;
|
||||
this.timestamp = timestamp;
|
||||
this.message = message;
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public int getStatusCode() {
|
||||
return statusCode;
|
||||
}
|
||||
|
||||
public Date getTimestamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.jambotronGroup.jambotron.exceptionHandlers;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import com.jambotronGroup.jambotron.exceptions.TokenRefreshException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.context.request.WebRequest;
|
||||
|
||||
|
||||
@RestControllerAdvice
|
||||
public class TokenControllerAdvice {
|
||||
|
||||
@ExceptionHandler(value = TokenRefreshException.class)
|
||||
@ResponseStatus(HttpStatus.FORBIDDEN)
|
||||
public ErrorMessage handleTokenRefreshException(TokenRefreshException ex, WebRequest request) {
|
||||
return new ErrorMessage(
|
||||
HttpStatus.FORBIDDEN.value(),
|
||||
new Date(),
|
||||
ex.getMessage(),
|
||||
request.getDescription(false));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.jambotronGroup.jambotron.exceptions;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
@ResponseStatus(HttpStatus.FORBIDDEN)
|
||||
public class TokenRefreshException extends RuntimeException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public TokenRefreshException(String token, String message) {
|
||||
super(String.format("Failed for [%s]: %s", token, message));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.jambotronGroup.jambotron.model;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Entity(name = "refreshtoken")
|
||||
public class RefreshToken {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private long id;
|
||||
|
||||
@OneToOne
|
||||
@JoinColumn(name = "user_id", referencedColumnName = "id")
|
||||
private User user;
|
||||
|
||||
@Column(nullable = false, unique = true)
|
||||
private String token;
|
||||
|
||||
@Column(nullable = false)
|
||||
private Instant expiryDate;
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public User getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setUser(User user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public String getToken() {
|
||||
return token;
|
||||
}
|
||||
|
||||
public void setToken(String token) {
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
public Instant getExpiryDate() {
|
||||
return expiryDate;
|
||||
}
|
||||
|
||||
public void setExpiryDate(Instant expiryDate) {
|
||||
this.expiryDate = expiryDate;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.jambotronGroup.jambotron.repository;
|
||||
|
||||
import com.jambotronGroup.jambotron.model.RefreshToken;
|
||||
import com.jambotronGroup.jambotron.model.User;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface RefreshTokenRepository extends JpaRepository<RefreshToken, Long> {
|
||||
Optional<RefreshToken> findByToken(String token);
|
||||
|
||||
@Modifying
|
||||
int deleteByUser(User user);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.jambotronGroup.jambotron.security.jwt;
|
||||
|
||||
|
||||
|
||||
import com.jambotronGroup.jambotron.model.User;
|
||||
import com.jambotronGroup.jambotron.security.services.UserDetailsImpl;
|
||||
import io.jsonwebtoken.*;
|
||||
import io.jsonwebtoken.io.Decoders;
|
||||
@@ -31,6 +32,9 @@ public class JwtUtils {
|
||||
@Value("${app.jwtCookieName}")
|
||||
private String jwtCookie;
|
||||
|
||||
@Value("${app.jwtRefreshCookieName}")
|
||||
private String jwtRefreshCookie;
|
||||
|
||||
public String getJwtFromCookies(HttpServletRequest request) {
|
||||
Cookie cookie = WebUtils.getCookie(request, jwtCookie);
|
||||
if (cookie != null) {
|
||||
@@ -46,6 +50,38 @@ public class JwtUtils {
|
||||
return cookie;
|
||||
}
|
||||
|
||||
public ResponseCookie generateRefreshJwtCookie(String refreshToken) {
|
||||
return generateCookie(jwtRefreshCookie, refreshToken, "/api/auth/refreshtoken");
|
||||
}
|
||||
|
||||
public String getJwtRefreshFromCookies(HttpServletRequest request) {
|
||||
return getCookieValueByName(request, jwtRefreshCookie);
|
||||
}
|
||||
|
||||
public ResponseCookie getCleanJwtRefreshCookie() {
|
||||
ResponseCookie cookie = ResponseCookie.from(jwtRefreshCookie, null).path("/api/auth/refreshtoken").build();
|
||||
return cookie;
|
||||
}
|
||||
|
||||
public ResponseCookie generateJwtCookie(User user) {
|
||||
String jwt = generateTokenFromUsername(user.getUsername());
|
||||
return generateCookie(jwtCookie, jwt, "/api");
|
||||
}
|
||||
|
||||
private ResponseCookie generateCookie(String name, String value, String path) {
|
||||
ResponseCookie cookie = ResponseCookie.from(name, value).path(path).maxAge(24 * 60 * 60).httpOnly(true).build();
|
||||
return cookie;
|
||||
}
|
||||
|
||||
private String getCookieValueByName(HttpServletRequest request, String name) {
|
||||
Cookie cookie = WebUtils.getCookie(request, name);
|
||||
if (cookie != null) {
|
||||
return cookie.getValue();
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public ResponseCookie getCleanJwtCookie() {
|
||||
ResponseCookie cookie = ResponseCookie.from(jwtCookie, null).path("/api").build();
|
||||
return cookie;
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.jambotronGroup.jambotron.security.services;
|
||||
|
||||
import com.jambotronGroup.jambotron.exceptions.TokenRefreshException;
|
||||
import com.jambotronGroup.jambotron.model.RefreshToken;
|
||||
import com.jambotronGroup.jambotron.repository.RefreshTokenRepository;
|
||||
import com.jambotronGroup.jambotron.repository.UserRepository;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
public class RefreshTokenService {
|
||||
@Value("${app.jwtRefreshExpirationMs}")
|
||||
private Long refreshTokenDurationMs;
|
||||
|
||||
@Autowired
|
||||
private RefreshTokenRepository refreshTokenRepository;
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
public Optional<RefreshToken> findByToken(String token) {
|
||||
return refreshTokenRepository.findByToken(token);
|
||||
}
|
||||
|
||||
public RefreshToken createRefreshToken(Long userId) {
|
||||
RefreshToken refreshToken = new RefreshToken();
|
||||
|
||||
refreshToken.setUser(userRepository.findById(userId).get());
|
||||
refreshToken.setExpiryDate(Instant.now().plusMillis(refreshTokenDurationMs));
|
||||
refreshToken.setToken(UUID.randomUUID().toString());
|
||||
|
||||
refreshToken = refreshTokenRepository.save(refreshToken);
|
||||
return refreshToken;
|
||||
}
|
||||
|
||||
public RefreshToken verifyExpiration(RefreshToken token) {
|
||||
if (token.getExpiryDate().compareTo(Instant.now()) < 0) {
|
||||
refreshTokenRepository.delete(token);
|
||||
throw new TokenRefreshException(token.getToken(), "Refresh token was expired. Please make a new signin request");
|
||||
}
|
||||
|
||||
return token;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public int deleteByUserId(Long userId) {
|
||||
return refreshTokenRepository.deleteByUser(userRepository.findById(userId).get());
|
||||
}
|
||||
}
|
||||
@@ -5,14 +5,14 @@ spring.application.name=jambotron
|
||||
server.port=8082
|
||||
#============Localhost Configurations========================
|
||||
|
||||
spring.datasource.url= jdbc:postgresql://localhost:5432/jambotronDB
|
||||
spring.datasource.url= jdbc:postgresql://localhost:5433/jambotronDB
|
||||
spring.datasource.username= admin
|
||||
spring.datasource.password= postgrespw
|
||||
|
||||
spring.flyway.baseline-on-migrate=true
|
||||
spring.flyway.validate-on-migrate=true
|
||||
|
||||
spring.flyway.url=jdbc:postgresql://localhost:5432/jambotronDB
|
||||
spring.flyway.url=jdbc:postgresql://localhost:5433/jambotronDB
|
||||
spring.flyway.user=admin
|
||||
spring.flyway.password=postgrespw
|
||||
|
||||
@@ -30,9 +30,14 @@ spring.ai.zhipuai.api-key = 628447c8c65845a48a7226391464a2ea.Dw8ci6TiW0BRF5LI
|
||||
|
||||
|
||||
#============ Custom App Properties
|
||||
app.jwtSecret= ======================spring=back====================
|
||||
app.jwtExpirationMs= 800000
|
||||
app.jwtCookieName=springangularts
|
||||
app.jwtSecret= ======================jambotron=back=================
|
||||
app.jwtCookieName=jambotron-jwt-cookie
|
||||
app.jwtRefreshCookieName= jambotron-jwt-cookie-refresh
|
||||
#app.jwtExpirationMs= 800000
|
||||
#app.jwtRefreshExpirationMs= 86400000
|
||||
|
||||
app.jwtExpirationMs= 30000
|
||||
app.jwtRefreshExpirationMs= 60000
|
||||
|
||||
#=============File Upload Configurations========================
|
||||
spring.servlet.multipart.max-file-size=50MB
|
||||
|
||||
Reference in New Issue
Block a user