Skip to content

Commit

Permalink
Fixes Jwt Request filter logic by white lists (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
petruki committed Mar 17, 2024
1 parent c3b138c commit d69022e
Show file tree
Hide file tree
Showing 11 changed files with 65 additions and 63 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,20 +27,19 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
throws ServletException, IOException {

final Optional<String> jwt = getJwtFromRequest(request);
jwt.ifPresent(token -> {
try {
String username = jwtTokenService.getUsernameFromToken(token);
if (Boolean.TRUE.equals(jwtTokenService.validateToken(token, username))) {
final UsernamePasswordAuthenticationToken authUser =
new UsernamePasswordAuthenticationToken(username, null, new ArrayList<>());
authUser.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

SecurityContextHolder.getContext().setAuthentication(authUser);
}
} catch (IllegalArgumentException | MalformedJwtException | ExpiredJwtException | SignatureException e) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
});
try {
jwt.ifPresent(token -> {
String username = jwtTokenService.getUsernameFromToken(token);
if (Boolean.TRUE.equals(jwtTokenService.validateToken(token, username))) {
final var authUser = new UsernamePasswordAuthenticationToken(username, null, new ArrayList<>());
authUser.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authUser);
}
});
} catch (IllegalArgumentException | MalformedJwtException | ExpiredJwtException | SignatureException e) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}

filterChain.doFilter(request, response);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ public class MultiTenantSecurityConfig extends SecurityConfig {
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth ->
auth.requestMatchers(allowedEndpoint).permitAll()
.requestMatchers("/**").access((authentication, object) -> buildAllowedIpList())
.requestMatchers(SWAGGER_MATCHERS).authenticated());
.requestMatchers(SWAGGER_MATCHERS).permitAll()
.requestMatchers("/**").access(this::authorize));

http.exceptionHandling(auth -> auth.authenticationEntryPoint(jwtAuthenticationEntryPoint));
http.sessionManagement(auth -> auth.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
Expand Down
12 changes: 3 additions & 9 deletions trackerforce-common/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@

<properties>
<jsonwebtoken.version>0.11.2</jsonwebtoken.version>
<springdoc.version>1.6.12</springdoc.version>
<springdoc-openapi-starter-webmvc-ui.version>2.4.0</springdoc-openapi-starter-webmvc-ui.version>

<!-- Test-->
<flapdoodle.embed.mongo.version>4.12.2</flapdoodle.embed.mongo.version>
Expand Down Expand Up @@ -114,14 +114,8 @@
<!-- Swagger 3 - SpringDoc OpenAPI -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>${springdoc.version}</version>
</dependency>

<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-security</artifactId>
<version>${springdoc.version}</version>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>${springdoc-openapi-starter-webmvc-ui.version}</version>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,12 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
import org.springframework.security.web.util.matcher.IpAddressMatcher;

import java.util.function.Supplier;

public abstract class SecurityConfig {

@Value("${service.endpoint.allowed-addresses}")
Expand All @@ -19,15 +23,23 @@ public abstract class SecurityConfig {
@Autowired
protected JwtRequestFilter jwtRequestFilter;

protected AuthorizationDecision buildAllowedIpList() {
AuthorizationDecision decision = new AuthorizationDecision(true);
protected AuthorizationDecision authorize(Supplier<Authentication> authentication, RequestAuthorizationContext object) {
final var remoteAddress = object.getRequest().getRemoteAddr();
var decision = new AuthorizationDecision(authentication.get().isAuthenticated());

boolean isAllowed = false;
for (String address : allowedAddresses) {
IpAddressMatcher ipAddressMatcher = new IpAddressMatcher(address);
if (!ipAddressMatcher.matches(address)) {
decision = new AuthorizationDecision(false);
if (ipAddressMatcher.matches(remoteAddress)) {
isAllowed = true;
break;
}
}

if (!isAllowed) {
decision = new AuthorizationDecision(false);
}

return decision;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package com.trackerforce.identity.config;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Optional;

import com.trackerforce.common.config.JwtRequestFilter;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.security.SignatureException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
Expand All @@ -13,34 +13,31 @@
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;

import com.trackerforce.common.config.JwtRequestFilter;

import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.security.SignatureException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Optional;

@Component
public class IdentityJwtRequestFilter extends JwtRequestFilter {

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {

final Optional<String> jwt = getJwtFromRequest(request);
jwt.ifPresent(token -> {
try {
try {
jwt.ifPresent(token -> {
String username = jwtTokenService.getUsernameFromToken(token);
if (Boolean.TRUE.equals(jwtTokenService.validateToken(token, username))) {
final UsernamePasswordAuthenticationToken authUser = new UsernamePasswordAuthenticationToken(
username, null, new ArrayList<>());
final var authUser = new UsernamePasswordAuthenticationToken(username, null, new ArrayList<>());
authUser.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

SecurityContextHolder.getContext().setAuthentication(authUser);
}
} catch (IllegalArgumentException | MalformedJwtException | ExpiredJwtException | SignatureException e) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
});
});
} catch (IllegalArgumentException | MalformedJwtException | ExpiredJwtException | SignatureException e) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}

filterChain.doFilter(request, response);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public class IdentitySecurityConfig extends SecurityConfig {
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth ->
auth.requestMatchers(allowedEndpoint).permitAll()
.requestMatchers("/**").authenticated());
.anyRequest().access(this::authorize));

http.exceptionHandling(auth -> auth.authenticationEntryPoint(jwtAuthenticationEntryPoint));
http.sessionManagement(auth -> auth.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
Expand Down
10 changes: 5 additions & 5 deletions trackerforce-identity/src/main/resources/application-dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ spring:
data:
mongodb:
database: trackerforce
uri: mongodb://master:masterpassword@localhost:27017
uri: mongodb://localhost:27017

management:
endpoints:
Expand All @@ -27,10 +27,10 @@ service:
10.0.0.2
allowed-endpoints: >
/v3/api-docs,
/**/swagger*/**,
/**/authenticate,
/**/register,
/**/activate,
/*/swagger*/**,
/*/authenticate,
/*/register,
/*/activate,
/service/check
management:
url: http://127.0.0.1:8090
Expand Down
6 changes: 3 additions & 3 deletions trackerforce-identity/src/main/resources/application-prod.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ service:
allowed-addresses: ${WHITELIST}
allowed-endpoints: >
/v3/api-docs,
/**/authenticate,
/**/register,
/**/activate,
/*/authenticate,
/*/register,
/*/activate,
/service/check
management:
url: http://127.0.0.1:8090
Expand Down
8 changes: 4 additions & 4 deletions trackerforce-identity/src/test/resources/application-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ service:
127.0.0.1
allowed-endpoints: >
/v2/api-docs,
/**/swagger*/**,
/**/authenticate,
/**/register,
/**/activate,
/*/swagger*/**,
/*/authenticate,
/*/register,
/*/activate,
/service/check
management:
url: http://127.0.0.1:8090
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ spring:
data:
mongodb:
database: tfm
uri: mongodb://master:masterpassword@localhost:27017
uri: mongodb://localhost:27017

management:
endpoints:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ spring:
data:
mongodb:
database: tfs
uri: mongodb://master:masterpassword@localhost:27017
uri: mongodb://localhost:27017

management:
endpoints:
Expand Down

0 comments on commit d69022e

Please sign in to comment.