| | 1 | = Други Развојни Активности = |
| | 2 | |
| | 3 | == Анализа на перформанси == |
| | 4 | |
| | 5 | == Безбедност и заштита == |
| | 6 | |
| | 7 | === JWT Token Authorization (Spring Security) === |
| | 8 | |
| | 9 | JWT (JSON Web Token) e stateless начин на автентикација - server НЕ чува информации за активни сесии во база, туку сите потребни податоци се во самиот token кој корисникот го чува локално/cookie. JWT содржи енкодирана json структура на информации (user_id, email, role, expiry...). |
| | 10 | |
| | 11 | Java код во Spring Boot: |
| | 12 | {{{ |
| | 13 | @Configuration |
| | 14 | @Getter @Setter |
| | 15 | @ConfigurationProperties(prefix = "auth") |
| | 16 | public class AuthProperties { |
| | 17 | private String secret; |
| | 18 | private int accessTokenMaxAge; |
| | 19 | private int refreshTokenMaxAge; |
| | 20 | } |
| | 21 | |
| | 22 | |
| | 23 | @Configuration |
| | 24 | @EnableWebSecurity |
| | 25 | public class SecurityConfig { |
| | 26 | |
| | 27 | private final JwtAuthenticationFilter jwtAuthenticationFilter; |
| | 28 | |
| | 29 | public SecurityConfig(JwtAuthenticationFilter jwtAuthenticationFilter) { |
| | 30 | this.jwtAuthenticationFilter = jwtAuthenticationFilter; |
| | 31 | } |
| | 32 | |
| | 33 | @Bean |
| | 34 | public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { |
| | 35 | http |
| | 36 | .csrf(AbstractHttpConfigurer::disable) |
| | 37 | .cors(Customizer.withDefaults()) |
| | 38 | .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) |
| | 39 | .httpBasic(AbstractHttpConfigurer::disable) |
| | 40 | .formLogin(AbstractHttpConfigurer::disable) |
| | 41 | .authorizeHttpRequests(auth -> auth |
| | 42 | .requestMatchers("/api/auth/**").permitAll() |
| | 43 | .anyRequest().authenticated()); |
| | 44 | |
| | 45 | http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); |
| | 46 | return http.build(); |
| | 47 | } |
| | 48 | }}} |
| | 49 | |
| | 50 | |
| | 51 | === Хеширање на пасворди (BCrypt) === |
| | 52 | |
| | 53 | Пасвордите на корисниците се чуваат во база во хеширана форма преку BCrypt, а не како plain text. Ова овозможува сигурно чување на пасвордите. |
| | 54 | |
| | 55 | {{{ |
| | 56 | public class LegacyPasswordEncoder implements PasswordEncoder { |
| | 57 | |
| | 58 | private final BCryptPasswordEncoder bcrypt = new BCryptPasswordEncoder(); |
| | 59 | |
| | 60 | @Override |
| | 61 | public String encode(CharSequence rawPassword) { |
| | 62 | return bcrypt.encode(rawPassword); |
| | 63 | } |
| | 64 | |
| | 65 | @Override |
| | 66 | public boolean matches(CharSequence rawPassword, String encodedPassword) { |
| | 67 | if (encodedPassword == null || encodedPassword.isEmpty()) { |
| | 68 | return false; |
| | 69 | } |
| | 70 | if (encodedPassword.startsWith("$2a$") || encodedPassword.startsWith("$2b$")) { |
| | 71 | return bcrypt.matches(rawPassword, encodedPassword); |
| | 72 | } |
| | 73 | return rawPassword.toString().equals(encodedPassword); |
| | 74 | } |
| | 75 | } |
| | 76 | }}} |
| | 77 | |
| | 78 | === SQL Injection Prevention (Spring JPA/JPQL) |
| | 79 | |
| | 80 | Целиот backend користи Spring Data JPA која автоматски генерира параметризирани пропити што спречуваат SQL injection. |
| | 81 | |
| | 82 | ==== Безбедно: Derived Query Methods ==== |
| | 83 | |
| | 84 | {{{ |
| | 85 | // UserRepository.java |
| | 86 | public interface UserRepository extends JpaRepository<User, Long> { |
| | 87 | Optional<User> findByEmail(String email); |
| | 88 | Optional<User> findByUsername(String username); |
| | 89 | } |
| | 90 | |
| | 91 | |
| | 92 | // SELECT * FROM users WHERE email = ? |
| | 93 | // параметарот се праќа одвоено од SQL командата |
| | 94 | }}} |
| | 95 | |
| | 96 | ==== Безбедно: @Query со @Param ==== |
| | 97 | |
| | 98 | {{{ |
| | 99 | // TaskRepository.java |
| | 100 | @Modifying |
| | 101 | @Query("update Task t set t.finished = false where t.disciplineUser.userId = :userId") |
| | 102 | int resetFinishedForUser(@Param("userId") Long userId); |
| | 103 | |
| | 104 | // Параметарот :userId се врзува безбедно преку JDBC, не преку string concatenation |
| | 105 | }}} |
| | 106 | |
| | 107 | ==== Безбедно: Collection параметри ==== |
| | 108 | |
| | 109 | {{{ |
| | 110 | // TrainingSessionRepository.java |
| | 111 | @java.util.List<TrainingSession> findByTrainingUser_UserIdAndDateIn( |
| | 112 | Long userId, |
| | 113 | Collection<LocalDate> dates |
| | 114 | ); |
| | 115 | |
| | 116 | |
| | 117 | === CORS Configuration === |
| | 118 | |
| | 119 | CORS е безбеден механизам за заштита од requests од различни домени. Со тоа се заштитуваме од можни злонамерни requests. |
| | 120 | |
| | 121 | Java код во Spring Boot: |
| | 122 | {{{ |
| | 123 | @Bean |
| | 124 | public CorsConfigurationSource corsConfigurationSource() { |
| | 125 | CorsConfiguration config = new CorsConfiguration(); |
| | 126 | config.setAllowedOrigins(List.of( |
| | 127 | "http://localhost:5173", |
| | 128 | "http://127.0.0.1:5173")); |
| | 129 | config.setAllowedMethods(List.of("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")); |
| | 130 | config.setAllowedHeaders(List.of("Authorization", "Content-Type", "Accept", "Origin", "X-Requested-With")); |
| | 131 | config.setAllowCredentials(true); |
| | 132 | |
| | 133 | UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); |
| | 134 | source.registerCorsConfiguration("/**", config); |
| | 135 | return source; |
| | 136 | } |
| | 137 | }}} |