incremental security changes
This commit is contained in:
23
pom.xml
23
pom.xml
@@ -58,6 +58,29 @@
|
|||||||
<version>2.0.2</version>
|
<version>2.0.2</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<!-- JWT Dependencies -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.jsonwebtoken</groupId>
|
||||||
|
<artifactId>jjwt-api</artifactId>
|
||||||
|
<version>0.11.5</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.jsonwebtoken</groupId>
|
||||||
|
<artifactId>jjwt-impl</artifactId>
|
||||||
|
<version>0.11.5</version>
|
||||||
|
<scope>runtime</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.jsonwebtoken</groupId>
|
||||||
|
<artifactId>jjwt-jackson</artifactId> <!-- or jjwt-gson, jjwt-orgjson -->
|
||||||
|
<version>0.11.5</version>
|
||||||
|
<scope>runtime</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-security</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
|||||||
18
src/main/java/org/zaine/app/config/OpenApiConfig.java
Normal file
18
src/main/java/org/zaine/app/config/OpenApiConfig.java
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
package org.zaine.app.config;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
|
||||||
|
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
|
||||||
|
import io.swagger.v3.oas.annotations.info.Info;
|
||||||
|
import io.swagger.v3.oas.annotations.security.SecurityScheme;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@OpenAPIDefinition(info = @Info(title = "org-backend API", version = "1.0.0"))
|
||||||
|
@SecurityScheme(
|
||||||
|
name = "bearerAuth", // referenced by name in controllers
|
||||||
|
type = SecuritySchemeType.HTTP,
|
||||||
|
scheme = "bearer",
|
||||||
|
bearerFormat = "JWT"
|
||||||
|
)
|
||||||
|
public class OpenApiConfig {
|
||||||
|
}
|
||||||
77
src/main/java/org/zaine/app/controller/AuthController.java
Normal file
77
src/main/java/org/zaine/app/controller/AuthController.java
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
// src/main/java/org/zaine/app/controller/AuthController.java
|
||||||
|
package org.zaine.app.controller;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import org.zaine.app.security.JwtUtil;
|
||||||
|
import org.zaine.app.user.User;
|
||||||
|
import org.zaine.app.user.UserRepository;
|
||||||
|
import org.springframework.http.*;
|
||||||
|
import org.springframework.security.authentication.*;
|
||||||
|
import org.springframework.security.core.AuthenticationException;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/auth")
|
||||||
|
@Tag(name = "Authentication")
|
||||||
|
public class AuthController {
|
||||||
|
|
||||||
|
private final JwtUtil jwtUtil;
|
||||||
|
private final AuthenticationManager authenticationManager;
|
||||||
|
private final UserRepository userRepository;
|
||||||
|
private final PasswordEncoder passwordEncoder;
|
||||||
|
|
||||||
|
public AuthController(JwtUtil jwtUtil,
|
||||||
|
AuthenticationManager authenticationManager,
|
||||||
|
UserRepository userRepository,
|
||||||
|
PasswordEncoder passwordEncoder) {
|
||||||
|
this.jwtUtil = jwtUtil;
|
||||||
|
this.authenticationManager = authenticationManager;
|
||||||
|
this.userRepository = userRepository;
|
||||||
|
this.passwordEncoder = passwordEncoder;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "Register a new user")
|
||||||
|
@PostMapping("/register")
|
||||||
|
public ResponseEntity<?> register(@RequestBody RegisterRequest req) {
|
||||||
|
if (userRepository.existsByUsername(req.username())) {
|
||||||
|
return ResponseEntity
|
||||||
|
.status(HttpStatus.CONFLICT)
|
||||||
|
.body(Map.of("error", "Username already taken"));
|
||||||
|
}
|
||||||
|
|
||||||
|
User user = new User();
|
||||||
|
user.setUsername(req.username());
|
||||||
|
user.setPassword(passwordEncoder.encode(req.password())); // BCrypt hash
|
||||||
|
user.setRole("ROLE_USER");
|
||||||
|
userRepository.save(user);
|
||||||
|
|
||||||
|
return ResponseEntity
|
||||||
|
.status(HttpStatus.CREATED)
|
||||||
|
.body(Map.of("message", "User registered successfully"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "Login and receive a JWT token")
|
||||||
|
@PostMapping("/login")
|
||||||
|
public ResponseEntity<?> login(@RequestBody LoginRequest req) {
|
||||||
|
try {
|
||||||
|
// This checks credentials against the DB via UserDetailsServiceImpl
|
||||||
|
authenticationManager.authenticate(
|
||||||
|
new UsernamePasswordAuthenticationToken(req.username(), req.password())
|
||||||
|
);
|
||||||
|
} catch (AuthenticationException e) {
|
||||||
|
return ResponseEntity
|
||||||
|
.status(HttpStatus.UNAUTHORIZED)
|
||||||
|
.body(Map.of("error", "Invalid username or password"));
|
||||||
|
}
|
||||||
|
|
||||||
|
String token = jwtUtil.generateToken(req.username());
|
||||||
|
return ResponseEntity.ok(Map.of("token", token));
|
||||||
|
}
|
||||||
|
|
||||||
|
public record LoginRequest(String username, String password) {}
|
||||||
|
public record RegisterRequest(String username, String password) {}
|
||||||
|
}
|
||||||
@@ -74,5 +74,16 @@ public class WirdController {
|
|||||||
WirdEntry saved = wirdService.createEntry(dto);
|
WirdEntry saved = wirdService.createEntry(dto);
|
||||||
return ResponseEntity.ok(saved);
|
return ResponseEntity.ok(saved);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* DELETE /api/wird/entries/{id}
|
||||||
|
* Deletes a log entry.
|
||||||
|
*/
|
||||||
|
@DeleteMapping("/entries/{id}")
|
||||||
|
public ResponseEntity<Void> deleteEntry(@PathVariable Long id) {
|
||||||
|
logger.log(Logger.Level.INFO, "Deleting wird entry with id: {0}", id);
|
||||||
|
wirdService.deleteEntry(id);
|
||||||
|
return ResponseEntity.noContent().build();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
74
src/main/java/org/zaine/app/security/JwtAuthFilter.java
Normal file
74
src/main/java/org/zaine/app/security/JwtAuthFilter.java
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
package org.zaine.app.security;
|
||||||
|
|
||||||
|
import jakarta.servlet.FilterChain;
|
||||||
|
import jakarta.servlet.ServletException;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||||
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
|
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.filter.OncePerRequestFilter;
|
||||||
|
import org.springframework.web.method.HandlerMethod;
|
||||||
|
import org.springframework.web.servlet.HandlerExecutionChain;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class JwtAuthFilter extends OncePerRequestFilter {
|
||||||
|
|
||||||
|
private final JwtUtil jwtUtil;
|
||||||
|
private final RequestMappingHandlerMapping requestMappingHandlerMapping;
|
||||||
|
|
||||||
|
public JwtAuthFilter(JwtUtil jwtUtil, RequestMappingHandlerMapping requestMappingHandlerMapping) {
|
||||||
|
this.jwtUtil = jwtUtil;
|
||||||
|
this.requestMappingHandlerMapping = requestMappingHandlerMapping;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void doFilterInternal(HttpServletRequest request,
|
||||||
|
HttpServletResponse response,
|
||||||
|
FilterChain filterChain) throws ServletException, IOException {
|
||||||
|
if (!endpointRequiresAuth(request)) {
|
||||||
|
filterChain.doFilter(request, response);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
String authHeader = request.getHeader("Authorization");
|
||||||
|
|
||||||
|
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
|
||||||
|
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing or invalid Authorization header");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
String token = authHeader.substring(7);
|
||||||
|
|
||||||
|
if (!jwtUtil.isTokenValid(token)) {
|
||||||
|
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid or expired token");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
String username = jwtUtil.extractUsername(token);
|
||||||
|
var auth = new UsernamePasswordAuthenticationToken(username, null, List.of());
|
||||||
|
auth.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
|
||||||
|
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||||
|
|
||||||
|
filterChain.doFilter(request, response);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean endpointRequiresAuth(HttpServletRequest request) {
|
||||||
|
try {
|
||||||
|
HandlerExecutionChain chain = requestMappingHandlerMapping.getHandler(request);
|
||||||
|
if (chain == null) return false;
|
||||||
|
Object handler = chain.getHandler();
|
||||||
|
if (!(handler instanceof HandlerMethod method)) return false;
|
||||||
|
|
||||||
|
return method.hasMethodAnnotation(RequiresAuth.class)
|
||||||
|
|| method.getBeanType().isAnnotationPresent(RequiresAuth.class);
|
||||||
|
} catch (Exception e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
53
src/main/java/org/zaine/app/security/JwtUtil.java
Normal file
53
src/main/java/org/zaine/app/security/JwtUtil.java
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
package org.zaine.app.security;
|
||||||
|
|
||||||
|
import io.jsonwebtoken.*;
|
||||||
|
import io.jsonwebtoken.security.Keys;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.security.Key;
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class JwtUtil {
|
||||||
|
|
||||||
|
@Value("${jwt.secret}")
|
||||||
|
private String secret;
|
||||||
|
|
||||||
|
@Value("${jwt.expiration-ms:86400000}")
|
||||||
|
private long expirationMs;
|
||||||
|
|
||||||
|
private Key getSigningKey() {
|
||||||
|
return Keys.hmacShaKeyFor(secret.getBytes());
|
||||||
|
}
|
||||||
|
|
||||||
|
public String generateToken(String username) {
|
||||||
|
return Jwts.builder()
|
||||||
|
.setSubject(username)
|
||||||
|
.setIssuedAt(new Date())
|
||||||
|
.setExpiration(new Date(System.currentTimeMillis() + expirationMs))
|
||||||
|
.signWith(getSigningKey(), SignatureAlgorithm.HS256)
|
||||||
|
.compact();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String extractUsername(String token) {
|
||||||
|
return parseClaims(token).getSubject();
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isTokenValid(String token) {
|
||||||
|
try {
|
||||||
|
parseClaims(token);
|
||||||
|
return true;
|
||||||
|
} catch (JwtException | IllegalArgumentException e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Claims parseClaims(String token) {
|
||||||
|
return Jwts.parserBuilder()
|
||||||
|
.setSigningKey(getSigningKey())
|
||||||
|
.build()
|
||||||
|
.parseClaimsJws(token)
|
||||||
|
.getBody();
|
||||||
|
}
|
||||||
|
}
|
||||||
9
src/main/java/org/zaine/app/security/RequiresAuth.java
Normal file
9
src/main/java/org/zaine/app/security/RequiresAuth.java
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
package org.zaine.app.security;
|
||||||
|
|
||||||
|
import java.lang.annotation.*;
|
||||||
|
|
||||||
|
@Target({ElementType.METHOD, ElementType.TYPE})
|
||||||
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
|
@Documented
|
||||||
|
public @interface RequiresAuth {
|
||||||
|
}
|
||||||
66
src/main/java/org/zaine/app/security/SecurityConfig.java
Normal file
66
src/main/java/org/zaine/app/security/SecurityConfig.java
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
// src/main/java/org/zaine/app/security/SecurityConfig.java
|
||||||
|
package org.zaine.app.security;
|
||||||
|
|
||||||
|
import org.zaine.app.user.UserDetailsServiceImpl;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.security.authentication.*;
|
||||||
|
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
|
||||||
|
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
|
||||||
|
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||||
|
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||||
|
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||||
|
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
import org.springframework.security.web.SecurityFilterChain;
|
||||||
|
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@EnableWebSecurity
|
||||||
|
public class SecurityConfig {
|
||||||
|
|
||||||
|
private final JwtAuthFilter jwtAuthFilter;
|
||||||
|
private final UserDetailsServiceImpl userDetailsService;
|
||||||
|
|
||||||
|
public SecurityConfig(JwtAuthFilter jwtAuthFilter, UserDetailsServiceImpl userDetailsService) {
|
||||||
|
this.jwtAuthFilter = jwtAuthFilter;
|
||||||
|
this.userDetailsService = userDetailsService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||||
|
http
|
||||||
|
.csrf(csrf -> csrf.disable())
|
||||||
|
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||||
|
.authorizeHttpRequests(auth -> auth
|
||||||
|
.requestMatchers(
|
||||||
|
"/api/auth/**",
|
||||||
|
"/v3/api-docs/**",
|
||||||
|
"/swagger-ui/**",
|
||||||
|
"/swagger-ui.html"
|
||||||
|
).permitAll()
|
||||||
|
.anyRequest().permitAll()
|
||||||
|
)
|
||||||
|
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
|
||||||
|
|
||||||
|
return http.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public DaoAuthenticationProvider authenticationProvider() {
|
||||||
|
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
|
||||||
|
provider.setUserDetailsService(userDetailsService);
|
||||||
|
provider.setPasswordEncoder(passwordEncoder());
|
||||||
|
return provider;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
|
||||||
|
return config.getAuthenticationManager();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public PasswordEncoder passwordEncoder() {
|
||||||
|
return new BCryptPasswordEncoder();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ import org.springframework.stereotype.Service;
|
|||||||
import org.zaine.app.dto.WirdEntryDTO;
|
import org.zaine.app.dto.WirdEntryDTO;
|
||||||
import org.zaine.app.model.WirdEntry;
|
import org.zaine.app.model.WirdEntry;
|
||||||
import org.zaine.app.repositories.WirdEntryRepository;
|
import org.zaine.app.repositories.WirdEntryRepository;
|
||||||
|
import java.lang.System.Logger;
|
||||||
|
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -12,6 +13,8 @@ import java.util.List;
|
|||||||
@Service
|
@Service
|
||||||
public class WirdService {
|
public class WirdService {
|
||||||
|
|
||||||
|
private static final Logger logger = System.getLogger(WirdService.class.getName());
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private WirdEntryRepository repo;
|
private WirdEntryRepository repo;
|
||||||
|
|
||||||
@@ -39,4 +42,12 @@ public class WirdService {
|
|||||||
entry.setNotes(dto.getNotes());
|
entry.setNotes(dto.getNotes());
|
||||||
return repo.save(entry);
|
return repo.save(entry);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void deleteEntry(Long id) {
|
||||||
|
if (id == null) {
|
||||||
|
logger.log(System.Logger.Level.WARNING, "Entry id is null. Operation aborted.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
repo.deleteById(id);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
30
src/main/java/org/zaine/app/user/User.java
Normal file
30
src/main/java/org/zaine/app/user/User.java
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
package org.zaine.app.user;
|
||||||
|
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Table(name = "users")
|
||||||
|
public class User {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@Column(nullable = false, unique = true)
|
||||||
|
private String username;
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private String password; // stored as BCrypt hash
|
||||||
|
|
||||||
|
@Column(nullable = false)
|
||||||
|
private String role; // e.g. "ROLE_USER", "ROLE_ADMIN"
|
||||||
|
|
||||||
|
// Getters & setters
|
||||||
|
public Long getId() { return id; }
|
||||||
|
public String getUsername() { return username; }
|
||||||
|
public void setUsername(String username) { this.username = username; }
|
||||||
|
public String getPassword() { return password; }
|
||||||
|
public void setPassword(String password) { this.password = password; }
|
||||||
|
public String getRole() { return role; }
|
||||||
|
public void setRole(String role) { this.role = role; }
|
||||||
|
}
|
||||||
30
src/main/java/org/zaine/app/user/UserDetailsServiceImpl.java
Normal file
30
src/main/java/org/zaine/app/user/UserDetailsServiceImpl.java
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
// src/main/java/org/zaine/app/user/UserDetailsServiceImpl.java
|
||||||
|
package org.zaine.app.user;
|
||||||
|
|
||||||
|
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||||
|
import org.springframework.security.core.userdetails.*;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class UserDetailsServiceImpl implements UserDetailsService {
|
||||||
|
|
||||||
|
private final UserRepository userRepository;
|
||||||
|
|
||||||
|
public UserDetailsServiceImpl(UserRepository userRepository) {
|
||||||
|
this.userRepository = userRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||||
|
User user = userRepository.findByUsername(username)
|
||||||
|
.orElseThrow(() -> new UsernameNotFoundException("User not found: " + username));
|
||||||
|
|
||||||
|
return new org.springframework.security.core.userdetails.User(
|
||||||
|
user.getUsername(),
|
||||||
|
user.getPassword(),
|
||||||
|
List.of(new SimpleGrantedAuthority(user.getRole()))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
9
src/main/java/org/zaine/app/user/UserRepository.java
Normal file
9
src/main/java/org/zaine/app/user/UserRepository.java
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
package org.zaine.app.user;
|
||||||
|
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
public interface UserRepository extends JpaRepository<User, Long> {
|
||||||
|
Optional<User> findByUsername(String username);
|
||||||
|
boolean existsByUsername(String username);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user