diff --git a/src/main/java/org/ccalm/jwt/MainController.java b/src/main/java/org/ccalm/jwt/MainController.java index 65b6e51..8576c55 100644 --- a/src/main/java/org/ccalm/jwt/MainController.java +++ b/src/main/java/org/ccalm/jwt/MainController.java @@ -930,7 +930,7 @@ public class MainController implements ServletContextAware { //SecretKey key_a = new SecretKeySpec(Base64.getDecoder().decode(key_a_txt), "HmacSHA256"); String key_r_txt = Tools.genKey(); //SecretKey key_r = Keys.secretKeyFor(SignatureAlgorithm.HS256); //Генерю секретный ключ для рефреш токена - JSONObject token = new JSONObject(); + /*JSONObject token = new JSONObject(); token.put("iss",issuer_name); token.put("iat", Instant.now().getEpochSecond()); //время, когда был выпущен JWT; //token.put("nbf", Instant.now().getEpochSecond()); //время, начиная с которого может быть использован (не раньше, чем). @@ -942,9 +942,9 @@ public class MainController implements ServletContextAware { .put("id",json.getLong("user_id")) .put("name",json.getString("name")) .put("email",json.getString("email")) - ); + );*/ - // Время действия токена (например, 1 час) + // Время действия токена Date expirationDate = new Date(System.currentTimeMillis() + refresh_time * 1000); Map claims = new HashMap<>(); @@ -1625,10 +1625,10 @@ public class MainController implements ServletContextAware { public ResponseEntity alive(HttpServletResponse response,HttpServletRequest request, Authentication authentication, @CookieValue(value = "lng",defaultValue="1") String language_id) { Translation trt = new Translation(language_id,jdbcTemplate); try { -++++++++++++ - String username = authentication.getName(); - return ResponseEntity.ok("User: " + username); - + if (authentication == null || !authentication.isAuthenticated()) { + throw new CustomException(10000, Collections.singletonList(trt.trt("Please_log_in")),null); + } + UserDetails userDetails = (UserDetails) authentication.getPrincipal(); /*if(jwt_a.isEmpty() || countOccurrences(jwt_a, '.')!=2) { throw new CustomException(10000, Collections.singletonList(trt.trt("Please_log_in")),null); @@ -1647,7 +1647,7 @@ public class MainController implements ServletContextAware { String result=null; try(Cache cache = new Cache(redis_host,redis_port,redis_password)) { cache.open(); - String data = cache.get(claims.getSignature()); + String data = cache.get(userDetails.getSignature()); if (data != null) { logout(response,request); if (data.equals("repeat")) { diff --git a/src/main/java/org/ccalm/jwt/SecurityConfig.java b/src/main/java/org/ccalm/jwt/SecurityConfig.java index 9ff4e67..1545613 100644 --- a/src/main/java/org/ccalm/jwt/SecurityConfig.java +++ b/src/main/java/org/ccalm/jwt/SecurityConfig.java @@ -1,5 +1,6 @@ package org.ccalm.jwt; +import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; @@ -9,9 +10,11 @@ import io.jsonwebtoken.Jws; import io.jsonwebtoken.Jwts; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.ccalm.jwt.models.ErrorResponseModel; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; @@ -45,8 +48,14 @@ public class SecurityConfig { public class JwtAuthFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { - // 🔹 Закомментировал проверку JWT, чтобы отключить авторизацию - /* + + // Данные пользователя, которые нужно передать + String email = ""; + String username = ""; + Long userId = 0L; + String signature = ""; + + //String jwt_a = extractTokenFromHeader(request); String jwt_a = null; if (request.getCookies() != null) { for (var cookie : request.getCookies()) { @@ -56,30 +65,48 @@ public class SecurityConfig { } } } - - if (jwt_a == null || jwt_a.isEmpty()) { - response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); + //Simple check + if (jwt_a == null || !jwt_a.contains(".")) { + ErrorResponseModel errorResponse = new ErrorResponseModel( + 10000 + HttpServletResponse.SC_UNAUTHORIZED, + List.of("Please_log_in", "Please_send_a_valid_JWT_token"), + "" + ); + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401 Unauthorized + response.setContentType("application/json"); + response.getWriter().write(new ObjectMapper().writeValueAsString(errorResponse)); // Отправляем ошибку в формате JSON return; } - + //Validate JWT token try { Jws claims = Jwts.parserBuilder() .setSigningKey(getPublicKey()) .build() .parseClaimsJws(jwt_a); + //signature = claims.getSignature(); + userId = Long.parseLong(claims.getBody().get("user_id").toString()); } catch (Exception e) { - response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid Token"); + } + + if(userId==0L) { + ErrorResponseModel errorResponse = new ErrorResponseModel( + 10000 + HttpServletResponse.SC_UNAUTHORIZED, + List.of("Please_log_in"), + "" + ); + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401 Unauthorized + response.setContentType("application/json"); + response.getWriter().write(new ObjectMapper().writeValueAsString(errorResponse)); // Отправляем ошибку в формате JSON return; } - */ - - // Создаём фиктивного пользователя с ролью "USER" - var authorities = List.of(new SimpleGrantedAuthority("ROLE_USER")); - var authentication = new UsernamePasswordAuthenticationToken("testUser", null, authorities); - + //Проверка на переавторизацию + List authorities = List.of(new SimpleGrantedAuthority("ROLE_USER")); + // Создаём пользователя с дополнительными данными + UserDetails userDetails = new UserDetails(email, username, userId, signature, authorities); + // Создаём аутентификацию + var authentication = new UsernamePasswordAuthenticationToken(userDetails, null, authorities); // Устанавливаем пользователя в SecurityContextHolder SecurityContextHolder.getContext().setAuthentication(authentication); - // Пропускаем дальше filterChain.doFilter(request, response); } @@ -110,4 +137,14 @@ public class SecurityConfig { } return null; } + + // Метод для извлечения токена из заголовка Authorization + private String extractTokenFromHeader(HttpServletRequest request) { + String header = request.getHeader("Authorization"); + if (header != null && header.startsWith("Bearer ")) { + return header.substring(7); // Возвращаем токен, убрав "Bearer " (7 символов) + } + return null; + } + } diff --git a/src/main/java/org/ccalm/jwt/UserDetails.java b/src/main/java/org/ccalm/jwt/UserDetails.java new file mode 100644 index 0000000..13e1a8b --- /dev/null +++ b/src/main/java/org/ccalm/jwt/UserDetails.java @@ -0,0 +1,69 @@ +package org.ccalm.jwt; + +import org.springframework.security.core.GrantedAuthority; + +import java.util.Collection; +import java.util.List; + +public class UserDetails implements org.springframework.security.core.userdetails.UserDetails { + private String email; + private String username; + private Long userId; + private String signature; + private List authorities; + + public UserDetails(String email, String username, Long userId,String signature, List authorities) { + this.email = email; + this.username = username; + this.userId = userId; + this.signature = signature; + this.authorities = authorities; + } + + @Override + public Collection getAuthorities() { + return authorities; + } + + @Override + public String getPassword() { + return null; // если пароль не нужен + } + + @Override + public String getUsername() { + return username; + } + + public String getEmail() { + return email; + } + + public Long getUserId() { + return userId; + } + + public String getSignature(){ + return signature; + } + + @Override + public boolean isAccountNonExpired() { + return true; + } + + @Override + public boolean isAccountNonLocked() { + return true; + } + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean isEnabled() { + return true; + } +}