-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
DEAR-105: add cors, security config and JWT filter
- Loading branch information
Showing
16 changed files
with
448 additions
and
18 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
22 changes: 22 additions & 0 deletions
22
src/main/java/ch/fhnw/deardevbackend/config/CorsConfig.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
package ch.fhnw.deardevbackend.config; | ||
|
||
import org.springframework.context.annotation.Bean; | ||
import org.springframework.context.annotation.Configuration; | ||
import org.springframework.web.servlet.config.annotation.CorsRegistry; | ||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; | ||
|
||
@Configuration | ||
public class CorsConfig { | ||
@Bean | ||
public WebMvcConfigurer corsConfigurer() { | ||
return new WebMvcConfigurer() { | ||
@Override | ||
public void addCorsMappings(CorsRegistry registry) { | ||
registry.addMapping("/**") | ||
.allowedOrigins("http://localhost:3000") | ||
.allowedMethods("GET", "PUT", "POST", "PATCH", "DELETE", "OPTIONS") | ||
.allowCredentials(true); | ||
} | ||
}; | ||
} | ||
} |
48 changes: 48 additions & 0 deletions
48
src/main/java/ch/fhnw/deardevbackend/config/SecurityConfig.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
package ch.fhnw.deardevbackend.config; | ||
|
||
import ch.fhnw.deardevbackend.filter.JWTFilter; | ||
import org.springframework.beans.factory.annotation.Autowired; | ||
import org.springframework.context.annotation.Bean; | ||
import org.springframework.context.annotation.Configuration; | ||
import org.springframework.http.HttpStatus; | ||
import org.springframework.security.authentication.AuthenticationManager; | ||
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.annotation.web.configurers.AbstractHttpConfigurer; | ||
import org.springframework.security.config.http.SessionCreationPolicy; | ||
import org.springframework.security.web.SecurityFilterChain; | ||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; | ||
import org.springframework.security.web.authentication.logout.HttpStatusReturningLogoutSuccessHandler; | ||
|
||
@Configuration | ||
@EnableWebSecurity | ||
public class SecurityConfig { | ||
|
||
@Autowired | ||
private JWTFilter filter; | ||
|
||
@Bean | ||
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { | ||
http | ||
.csrf(AbstractHttpConfigurer::disable) | ||
.authorizeHttpRequests(authz -> authz | ||
.requestMatchers("/auth/token").permitAll() | ||
.anyRequest().authenticated()) | ||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) | ||
.formLogin(AbstractHttpConfigurer::disable) | ||
.logout(logout -> logout.logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK)) | ||
.deleteCookies("JSESSIONID").invalidateHttpSession(true)); | ||
|
||
http | ||
.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class); | ||
|
||
return http.build(); | ||
} | ||
|
||
@Bean | ||
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception { | ||
return authenticationConfiguration.getAuthenticationManager(); | ||
} | ||
|
||
} |
40 changes: 40 additions & 0 deletions
40
src/main/java/ch/fhnw/deardevbackend/controller/AuthController.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
package ch.fhnw.deardevbackend.controller; | ||
|
||
import ch.fhnw.deardevbackend.entities.User; | ||
import ch.fhnw.deardevbackend.services.UserService; | ||
import ch.fhnw.deardevbackend.util.JWTUtil; | ||
import org.springframework.beans.factory.annotation.Autowired; | ||
import org.springframework.http.ResponseEntity; | ||
import org.springframework.web.bind.annotation.PostMapping; | ||
import org.springframework.web.bind.annotation.RequestMapping; | ||
import org.springframework.web.bind.annotation.RequestParam; | ||
import org.springframework.web.bind.annotation.RestController; | ||
|
||
import java.util.Optional; | ||
|
||
@RestController | ||
@RequestMapping("/auth") | ||
public class AuthController { | ||
|
||
@Autowired | ||
private JWTUtil jwtUtil; | ||
|
||
@Autowired | ||
private UserService userService; | ||
|
||
@PostMapping("/token") | ||
public ResponseEntity<String> generateToken(@RequestParam String email, @RequestParam int id) { | ||
Optional<User> userOptional = userService.findUserByEmail(email); | ||
if (userOptional.isPresent()) { | ||
User user = userOptional.get(); | ||
if (user.getId() == id) { | ||
String token = jwtUtil.generateToken(user); | ||
return ResponseEntity.ok(token); | ||
} else { | ||
return ResponseEntity.status(401).body("User ID does not match."); | ||
} | ||
} else { | ||
return ResponseEntity.status(404).body("User not found"); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
73 changes: 73 additions & 0 deletions
73
src/main/java/ch/fhnw/deardevbackend/filter/JWTFilter.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
package ch.fhnw.deardevbackend.filter; | ||
|
||
import ch.fhnw.deardevbackend.entities.User; | ||
import ch.fhnw.deardevbackend.services.UserService; | ||
import ch.fhnw.deardevbackend.util.JWTUtil; | ||
import io.jsonwebtoken.ExpiredJwtException; | ||
import io.jsonwebtoken.MalformedJwtException; | ||
import jakarta.servlet.FilterChain; | ||
import jakarta.servlet.ServletException; | ||
import jakarta.servlet.http.HttpServletRequest; | ||
import jakarta.servlet.http.HttpServletResponse; | ||
import lombok.extern.slf4j.Slf4j; | ||
import org.springframework.beans.factory.annotation.Autowired; | ||
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 java.io.IOException; | ||
import java.util.ArrayList; | ||
import java.util.Optional; | ||
|
||
@Slf4j | ||
@Component | ||
public class JWTFilter extends OncePerRequestFilter { | ||
|
||
@Autowired | ||
private JWTUtil jwtUtil; | ||
|
||
@Autowired | ||
private UserService userService; | ||
|
||
@Override | ||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { | ||
final String requestTokenHeader = request.getHeader("Authorization"); | ||
|
||
String email = null; | ||
String jwtToken = null; | ||
|
||
if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) { | ||
jwtToken = requestTokenHeader.substring(7); | ||
try { | ||
email = jwtUtil.extractEmail(jwtToken); | ||
} catch (IllegalArgumentException e) { | ||
log.warn("Unable to get JWT Token"); | ||
} catch (ExpiredJwtException e) { | ||
log.warn("JWT Token has expired"); | ||
} catch (MalformedJwtException e) { | ||
log.warn("JWT Token is invalid"); | ||
} | ||
} else { | ||
log.warn("JWT Token does not begin with Bearer String"); | ||
} | ||
|
||
if (email != null && SecurityContextHolder.getContext().getAuthentication() == null) { | ||
Optional<User> userOptional = userService.findUserByEmail(email); | ||
if (userOptional.isPresent()) { | ||
User user = userOptional.get(); | ||
if (jwtUtil.validateToken(jwtToken, user)) { | ||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( | ||
user, null, new ArrayList<>()); | ||
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); | ||
SecurityContextHolder.getContext().setAuthentication(authentication); | ||
} else { | ||
log.warn("JWT Token is not valid or expired"); | ||
} | ||
} | ||
} | ||
chain.doFilter(request, response); | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
package ch.fhnw.deardevbackend.util; | ||
|
||
import ch.fhnw.deardevbackend.entities.User; | ||
import io.jsonwebtoken.Claims; | ||
import io.jsonwebtoken.Jwts; | ||
import io.jsonwebtoken.SignatureException; | ||
import org.springframework.beans.factory.annotation.Value; | ||
import org.springframework.stereotype.Component; | ||
|
||
import java.util.Date; | ||
import java.util.function.Function; | ||
|
||
@Component | ||
public class JWTUtil { | ||
|
||
@Value("${jwt.secret}") | ||
private String secret; | ||
|
||
public String extractEmail(String token) { | ||
return extractClaim(token, claims -> claims.get("email", String.class)); | ||
} | ||
|
||
public int extractUserId(String token) { | ||
Claims claims = extractAllClaims(token); | ||
return claims.get("id", Integer.class); | ||
} | ||
|
||
public Date extractExpiration(String token) { | ||
return extractClaim(token, Claims::getExpiration); | ||
} | ||
|
||
public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) { | ||
final Claims claims = extractAllClaims(token); | ||
return claimsResolver.apply(claims); | ||
} | ||
|
||
private Claims extractAllClaims(String token) { | ||
try { | ||
return Jwts.parser() | ||
.setSigningKey(secret.getBytes()) | ||
.parseClaimsJws(token) | ||
.getBody(); | ||
} catch (SignatureException e) { | ||
throw new IllegalArgumentException("Invalid JWT signature"); | ||
} | ||
} | ||
|
||
private Boolean isTokenExpired(String token) { | ||
return extractExpiration(token).before(new Date()); | ||
} | ||
|
||
public Boolean validateToken(String token, User user) { | ||
final String email = extractEmail(token); | ||
final int tokenUserId = extractUserId(token); | ||
return (email.equals(user.getEmail()) && tokenUserId == user.getId() && !isTokenExpired(token)); | ||
} | ||
|
||
public String generateToken(User user) { | ||
return Jwts.builder() | ||
.claim("id", user.getId()) | ||
.claim("email", user.getEmail()) | ||
.setIssuedAt(new Date(System.currentTimeMillis())) | ||
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10)) | ||
.signWith(io.jsonwebtoken.SignatureAlgorithm.HS256, secret.getBytes()) | ||
.compact(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
13 changes: 0 additions & 13 deletions
13
src/test/java/ch/fhnw/deardevbackend/ApplicationTests.java
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.