Add JWT authentication filter to secure protected routes

- Intercepts all requests and checks for Bearer token.
- Validates token signature and expiry using JwtService.
- Loads user from DB and sets authentication context.
- Sends 401 Unauthorized if token is missing, invalid, or expired.
This commit is contained in:
K
2025-07-03 02:43:56 +05:30
parent 4b21828510
commit aaf5d2dbd8
2 changed files with 81 additions and 11 deletions
@@ -1,5 +1,6 @@
package com.skycrate.backend.skycrateBackend.config;
import com.skycrate.backend.skycrateBackend.security.JwtAuthenticationFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
@@ -7,22 +8,24 @@ import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.header.writers.HstsHeaderWriter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
public class SecurityConfig {
private final AuthenticationProvider authenticationProvider;
private final JwtAuthenticationFilter jwtAuthenticationFilter;
public SecurityConfig(AuthenticationProvider authenticationProvider) {
public SecurityConfig(AuthenticationProvider authenticationProvider,
JwtAuthenticationFilter jwtAuthenticationFilter) {
this.authenticationProvider = authenticationProvider;
this.jwtAuthenticationFilter = jwtAuthenticationFilter;
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable()) // if using JWT; enable if using sessions
.csrf(csrf -> csrf.disable())
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authenticationProvider(authenticationProvider)
.authorizeHttpRequests(auth -> auth
@@ -38,13 +41,10 @@ public class SecurityConfig {
.includeSubDomains(true)
.maxAgeInSeconds(31536000)
)
.xssProtection(xss -> xss
.block(true)
)
.frameOptions(frame -> frame
.deny()
)
);
.xssProtection(xss -> xss.block(true))
.frameOptions(frame -> frame.deny())
)
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}