WIP: Refresh token implemented in BE, yet to be implemented in FE
This commit is contained in:
+39
-3
@@ -1,20 +1,56 @@
|
|||||||
package com.adityachandel.booklore.config.security;
|
package com.adityachandel.booklore.config.security;
|
||||||
|
|
||||||
|
import com.adityachandel.booklore.exception.ApiError;
|
||||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||||
import com.adityachandel.booklore.model.entity.EpubViewerPreferencesEntity;
|
import com.adityachandel.booklore.model.dto.request.UserLoginRequest;
|
||||||
import com.adityachandel.booklore.repository.PdfViewerPreferencesRepository;
|
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||||
|
import com.adityachandel.booklore.repository.UserRepository;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import org.springframework.security.authentication.AuthenticationManager;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.security.core.Authentication;
|
import org.springframework.security.core.Authentication;
|
||||||
import org.springframework.security.core.context.SecurityContextHolder;
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
@Service
|
@Service
|
||||||
public class AuthenticationService {
|
public class AuthenticationService {
|
||||||
|
|
||||||
|
private final UserRepository userRepository;
|
||||||
|
private final PasswordEncoder passwordEncoder;
|
||||||
|
private final JwtUtils jwtUtils;
|
||||||
|
|
||||||
public BookLoreUser getAuthenticatedUser() {
|
public BookLoreUser getAuthenticatedUser() {
|
||||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||||
return (BookLoreUser) authentication.getPrincipal();
|
return (BookLoreUser) authentication.getPrincipal();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public ResponseEntity<Map<String, String>> loginUser(UserLoginRequest loginRequest) {
|
||||||
|
BookLoreUserEntity user = userRepository.findByUsername(loginRequest.getUsername()).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(loginRequest.getUsername()));
|
||||||
|
|
||||||
|
if (!passwordEncoder.matches(loginRequest.getPassword(), user.getPasswordHash())) {
|
||||||
|
throw ApiError.INVALID_CREDENTIALS.createException();
|
||||||
|
}
|
||||||
|
|
||||||
|
String accessToken = jwtUtils.generateAccessToken(user);
|
||||||
|
String refreshToken = jwtUtils.generateRefreshToken(user);
|
||||||
|
|
||||||
|
return ResponseEntity.ok(Map.of("accessToken", accessToken, "refreshToken", refreshToken));
|
||||||
|
}
|
||||||
|
|
||||||
|
public ResponseEntity<Map<String, String>> refreshToken(String refreshToken) {
|
||||||
|
if (!jwtUtils.validateToken(refreshToken)) {
|
||||||
|
throw ApiError.INVALID_CREDENTIALS.createException();
|
||||||
|
}
|
||||||
|
|
||||||
|
String username = jwtUtils.extractUsername(refreshToken);
|
||||||
|
BookLoreUserEntity user = userRepository.findByUsername(username).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(username));
|
||||||
|
|
||||||
|
String newAccessToken = jwtUtils.generateAccessToken(user);
|
||||||
|
String newRefreshToken = jwtUtils.generateRefreshToken(user);
|
||||||
|
|
||||||
|
return ResponseEntity.ok(Map.of("accessToken", newAccessToken, "refreshToken", newRefreshToken));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+33
-19
@@ -3,42 +3,58 @@ package com.adityachandel.booklore.config.security;
|
|||||||
import io.jsonwebtoken.*;
|
import io.jsonwebtoken.*;
|
||||||
import io.jsonwebtoken.security.Keys;
|
import io.jsonwebtoken.security.Keys;
|
||||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
import javax.crypto.SecretKey;
|
import javax.crypto.SecretKey;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
@Component
|
@Component
|
||||||
public class JwtUtils {
|
public class JwtUtils {
|
||||||
private final String secretKey = "G6u4m3g7M/b93k7m9a1h1Kw4l3D+5WqXldpl4nTjl4s=";
|
|
||||||
|
@Value("${security.jwt.secret}")
|
||||||
|
private String secretKey;
|
||||||
|
|
||||||
|
@Value("${security.jwt.expiration}")
|
||||||
|
private long accessTokenExpirationMs;
|
||||||
|
|
||||||
|
@Value("${security.jwt.refreshExpiration}")
|
||||||
|
private long refreshTokenExpirationMs;
|
||||||
|
|
||||||
private SecretKey getSigningKey() {
|
private SecretKey getSigningKey() {
|
||||||
return Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8));
|
return Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8));
|
||||||
}
|
}
|
||||||
|
|
||||||
public String generateToken(BookLoreUserEntity user) {
|
public String generateToken(BookLoreUserEntity user, boolean isRefreshToken) {
|
||||||
SecretKey key = getSigningKey();
|
long expirationTime = isRefreshToken ? refreshTokenExpirationMs : accessTokenExpirationMs;
|
||||||
Date now = new Date();
|
|
||||||
Date expirationDate = new Date(now.getTime() + 1000 * 60 * 60 * 10);
|
|
||||||
|
|
||||||
return Jwts.builder()
|
return Jwts.builder()
|
||||||
.subject(user.getUsername())
|
.subject(user.getUsername())
|
||||||
.claim("userId", user.getId())
|
.claim("userId", user.getId())
|
||||||
.issuedAt(now)
|
.issuedAt(new Date())
|
||||||
.expiration(expirationDate)
|
.expiration(new Date(System.currentTimeMillis() + expirationTime))
|
||||||
.signWith(key, Jwts.SIG.HS256)
|
.signWith(getSigningKey(), Jwts.SIG.HS256)
|
||||||
.compact();
|
.compact();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public String generateAccessToken(BookLoreUserEntity user) {
|
||||||
|
return generateToken(user, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String generateRefreshToken(BookLoreUserEntity user) {
|
||||||
|
return generateToken(user, true);
|
||||||
|
}
|
||||||
|
|
||||||
public boolean validateToken(String token) {
|
public boolean validateToken(String token) {
|
||||||
try {
|
try {
|
||||||
return !isTokenExpired(token);
|
extractClaims(token);
|
||||||
|
return true;
|
||||||
|
} catch (ExpiredJwtException e) {
|
||||||
|
System.out.println("Token expired: " + e.getMessage());
|
||||||
} catch (JwtException e) {
|
} catch (JwtException e) {
|
||||||
return false;
|
System.out.println("Invalid token: " + e.getMessage());
|
||||||
}
|
}
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Claims extractClaims(String token) {
|
public Claims extractClaims(String token) {
|
||||||
@@ -55,15 +71,13 @@ public class JwtUtils {
|
|||||||
|
|
||||||
public Long extractUserId(String token) {
|
public Long extractUserId(String token) {
|
||||||
Object userIdClaim = extractClaims(token).get("userId");
|
Object userIdClaim = extractClaims(token).get("userId");
|
||||||
if (userIdClaim instanceof Integer) {
|
if (userIdClaim instanceof Number) {
|
||||||
return ((Integer) userIdClaim).longValue();
|
return ((Number) userIdClaim).longValue();
|
||||||
} else if (userIdClaim instanceof Long) {
|
|
||||||
return (Long) userIdClaim;
|
|
||||||
}
|
}
|
||||||
throw new IllegalArgumentException("userId claim is not of type Long or Integer");
|
throw new IllegalArgumentException("Invalid userId claim type");
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean isTokenExpired(String token) {
|
public boolean isTokenExpired(String token) {
|
||||||
return extractClaims(token).getExpiration().before(new Date());
|
return extractClaims(token).getExpiration().before(new Date());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+10
-4
@@ -1,9 +1,10 @@
|
|||||||
package com.adityachandel.booklore.controller;
|
package com.adityachandel.booklore.controller;
|
||||||
|
|
||||||
|
import com.adityachandel.booklore.config.security.AuthenticationService;
|
||||||
import com.adityachandel.booklore.model.dto.UserCreateRequest;
|
import com.adityachandel.booklore.model.dto.UserCreateRequest;
|
||||||
|
import com.adityachandel.booklore.model.dto.request.RefreshTokenRequest;
|
||||||
import com.adityachandel.booklore.model.dto.request.UserLoginRequest;
|
import com.adityachandel.booklore.model.dto.request.UserLoginRequest;
|
||||||
import com.adityachandel.booklore.service.user.UserCreatorService;
|
import com.adityachandel.booklore.service.user.UserCreatorService;
|
||||||
import com.adityachandel.booklore.service.user.UserService;
|
|
||||||
import jakarta.validation.Valid;
|
import jakarta.validation.Valid;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
@@ -18,10 +19,10 @@ import java.util.Map;
|
|||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/api/v1/auth")
|
@RequestMapping("/api/v1/auth")
|
||||||
public class AuthController {
|
public class AuthenticationController {
|
||||||
|
|
||||||
private final UserCreatorService userCreatorService;
|
private final UserCreatorService userCreatorService;
|
||||||
private final UserService userService;
|
private final AuthenticationService authenticationService;
|
||||||
|
|
||||||
@PostMapping("/register")
|
@PostMapping("/register")
|
||||||
@PreAuthorize("@securityUtil.isAdmin()")
|
@PreAuthorize("@securityUtil.isAdmin()")
|
||||||
@@ -32,6 +33,11 @@ public class AuthController {
|
|||||||
|
|
||||||
@PostMapping("/login")
|
@PostMapping("/login")
|
||||||
public ResponseEntity<Map<String, String>> loginUser(@RequestBody @Valid UserLoginRequest loginRequest) {
|
public ResponseEntity<Map<String, String>> loginUser(@RequestBody @Valid UserLoginRequest loginRequest) {
|
||||||
return userService.loginUser(loginRequest);
|
return authenticationService.loginUser(loginRequest);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/refresh")
|
||||||
|
public ResponseEntity<Map<String, String>> refreshToken(@Valid @RequestBody RefreshTokenRequest request) {
|
||||||
|
return authenticationService.refreshToken(request.getRefreshToken());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+15
@@ -0,0 +1,15 @@
|
|||||||
|
package com.adityachandel.booklore.model.dto.request;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
import lombok.Setter;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@NoArgsConstructor
|
||||||
|
public class RefreshTokenRequest {
|
||||||
|
|
||||||
|
@NotBlank(message = "Refresh token must not be blank")
|
||||||
|
private String refreshToken;
|
||||||
|
}
|
||||||
@@ -29,22 +29,9 @@ public class UserService {
|
|||||||
|
|
||||||
private final UserRepository userRepository;
|
private final UserRepository userRepository;
|
||||||
private final BookLoreUserMapper bookLoreUserMapper;
|
private final BookLoreUserMapper bookLoreUserMapper;
|
||||||
private final PasswordEncoder passwordEncoder;
|
|
||||||
private final LibraryRepository libraryRepository;
|
private final LibraryRepository libraryRepository;
|
||||||
private final JwtUtils jwtUtils;
|
|
||||||
private final AuthenticationService authenticationService;
|
private final AuthenticationService authenticationService;
|
||||||
|
|
||||||
public ResponseEntity<Map<String, String>> loginUser(UserLoginRequest loginRequest) {
|
|
||||||
BookLoreUserEntity user = userRepository.findByUsername(loginRequest.getUsername()).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(loginRequest.getUsername()));
|
|
||||||
|
|
||||||
if (!passwordEncoder.matches(loginRequest.getPassword(), user.getPasswordHash())) {
|
|
||||||
throw ApiError.INVALID_CREDENTIALS.createException();
|
|
||||||
}
|
|
||||||
|
|
||||||
String token = jwtUtils.generateToken(user);
|
|
||||||
return ResponseEntity.ok(Map.of("token", token));
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<BookLoreUser> getBookLoreUsers() {
|
public List<BookLoreUser> getBookLoreUsers() {
|
||||||
return userRepository.findAll()
|
return userRepository.findAll()
|
||||||
.stream()
|
.stream()
|
||||||
|
|||||||
@@ -2,6 +2,12 @@ app:
|
|||||||
path-book: '/app/books'
|
path-book: '/app/books'
|
||||||
path-config: '/app/config'
|
path-config: '/app/config'
|
||||||
|
|
||||||
|
security:
|
||||||
|
jwt:
|
||||||
|
secret: G6u4m3g7M/b93k7m9a1h1Kw4l3D+5WqXldpl4nTjl4s=
|
||||||
|
expiration: 36000000 # 10 hours in milliseconds
|
||||||
|
refreshExpiration: 604800000 # 7 days in milliseconds
|
||||||
|
|
||||||
spring:
|
spring:
|
||||||
servlet:
|
servlet:
|
||||||
multipart:
|
multipart:
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import {AuthService} from './core/service/auth.service';
|
|||||||
export const AuthInterceptorService: HttpInterceptorFn = (req, next) => {
|
export const AuthInterceptorService: HttpInterceptorFn = (req, next) => {
|
||||||
const authService = inject(AuthService);
|
const authService = inject(AuthService);
|
||||||
const router = inject(Router);
|
const router = inject(Router);
|
||||||
const token = localStorage.getItem('token');
|
const token = localStorage.getItem('accessToken');
|
||||||
|
|
||||||
if (token) {
|
if (token) {
|
||||||
req = req.clone({
|
req = req.clone({
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import {CanActivateFn, Router} from '@angular/router';
|
|||||||
|
|
||||||
export const AuthGuard: CanActivateFn = (route, state) => {
|
export const AuthGuard: CanActivateFn = (route, state) => {
|
||||||
const router = inject(Router);
|
const router = inject(Router);
|
||||||
const token = localStorage.getItem('token');
|
const token = localStorage.getItem('accessToken');
|
||||||
|
|
||||||
if (!token) {
|
if (!token) {
|
||||||
router.navigate(['/login']);
|
router.navigate(['/login']);
|
||||||
|
|||||||
@@ -7,17 +7,17 @@ import { RxStompService } from '../../shared/websocket/rx-stomp.service';
|
|||||||
providedIn: 'root',
|
providedIn: 'root',
|
||||||
})
|
})
|
||||||
export class AuthService {
|
export class AuthService {
|
||||||
private apiUrl = 'http://localhost:7050/api/v1/auth/login';
|
private apiUrl = 'http://localhost:7050/api/v1/auth';
|
||||||
private rxStompService?: RxStompService;
|
private rxStompService?: RxStompService;
|
||||||
|
|
||||||
private http = inject(HttpClient);
|
private http = inject(HttpClient);
|
||||||
private injector = inject(Injector);
|
private injector = inject(Injector);
|
||||||
|
|
||||||
login(credentials: { username: string; password: string }): Observable<any> {
|
login(credentials: { username: string; password: string }): Observable<any> {
|
||||||
return this.http.post<{ token: string }>(this.apiUrl, credentials).pipe(
|
return this.http.post<{ accessToken: string; refreshToken: string }>(`${this.apiUrl}/login`, credentials).pipe(
|
||||||
tap((response) => {
|
tap((response) => {
|
||||||
if (response.token) {
|
if (response.accessToken && response.refreshToken) {
|
||||||
this.saveToken(response.token);
|
this.saveToken(response.accessToken);
|
||||||
this.getRxStompService().activate();
|
this.getRxStompService().activate();
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -25,15 +25,15 @@ export class AuthService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
saveToken(token: string): void {
|
saveToken(token: string): void {
|
||||||
localStorage.setItem('token', token);
|
localStorage.setItem('accessToken', token);
|
||||||
}
|
}
|
||||||
|
|
||||||
getToken(): string | null {
|
getToken(): string | null {
|
||||||
return localStorage.getItem('token');
|
return localStorage.getItem('accessToken');
|
||||||
}
|
}
|
||||||
|
|
||||||
logout(): void {
|
logout(): void {
|
||||||
localStorage.removeItem('token');
|
localStorage.removeItem('accessToken');
|
||||||
this.getRxStompService().deactivate();
|
this.getRxStompService().deactivate();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -6,8 +6,8 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.dashboard-scroller-no-books {
|
.dashboard-scroller-no-books {
|
||||||
padding-top: 3rem;
|
padding-top: 5rem;
|
||||||
padding-bottom: 3rem;
|
padding-bottom: 5rem;
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
|||||||
@@ -34,8 +34,7 @@ export class LoginComponent {
|
|||||||
|
|
||||||
login(): void {
|
login(): void {
|
||||||
this.authService.login({ username: this.username, password: this.password }).subscribe({
|
this.authService.login({ username: this.username, password: this.password }).subscribe({
|
||||||
next: (response) => {
|
next: () => {
|
||||||
this.authService.saveToken(response.token);
|
|
||||||
this.router.navigate(['/dashboard']);
|
this.router.navigate(['/dashboard']);
|
||||||
},
|
},
|
||||||
error: () => {
|
error: () => {
|
||||||
|
|||||||
@@ -64,7 +64,7 @@ export class UserService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private loadUserFromToken(): void {
|
private loadUserFromToken(): void {
|
||||||
const token = localStorage.getItem('token');
|
const token = localStorage.getItem('accessToken');
|
||||||
if (token) {
|
if (token) {
|
||||||
const decoded: JwtPayload = jwtDecode(token);
|
const decoded: JwtPayload = jwtDecode(token);
|
||||||
this.fetchUser(decoded.userId);
|
this.fetchUser(decoded.userId);
|
||||||
@@ -129,6 +129,6 @@ export class UserService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
getToken(): string | null {
|
getToken(): string | null {
|
||||||
return localStorage.getItem('token');
|
return localStorage.getItem('accessToken');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user