Skip to content

Commit

Permalink
refactored Filter in order to allow custom implementations
Browse files Browse the repository at this point in the history
  • Loading branch information
melistik committed Jul 11, 2018
1 parent 60a4649 commit 7d6b155
Showing 1 changed file with 16 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -36,22 +36,32 @@ public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
final String requestHeader = request.getHeader(jwtProperties.getHeader());
String authToken = getAuthToken(request);
String username = getValidatedUsername(authToken);

setAuthenticationIfValid(authToken, username, request);

chain.doFilter(request, response);
}

String username = null;
protected String getAuthToken(HttpServletRequest request) {
String authToken = null;

final String requestHeader = request.getHeader(jwtProperties.getHeader());
if (requestHeader != null && requestHeader.startsWith(jwtProperties.getTokenPrefix())) {
// check header
authToken = requestHeader.substring(jwtProperties.getTokenPrefix().length());
} else if (request.getParameter(jwtProperties.getUriParam()) != null) {
// check uiParam
authToken = request.getParameter(jwtProperties.getUriParam());
}
return authToken;
}

protected String getValidatedUsername(String authToken) {
if (authToken != null) {
try {
username = jwtTokenService.getUsernameFromToken(authToken);
return jwtTokenService.getUsernameFromToken(authToken);
} catch (IllegalArgumentException e) {
log.error("an error occured during getting username from token. {}", e.getMessage());
} catch (ExpiredJwtException e) {
Expand All @@ -62,10 +72,12 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
log.error("other token exception: {}", e.getMessage());
}
}
return null;
}

protected void setAuthenticationIfValid(String authToken, String username, HttpServletRequest request) {
if (username != null && SecurityContextHolder.getContext()
.getAuthentication() == null) {

AppUser user = (AppUser) appUserService.loadUserByUsername(username);

if (jwtTokenService.validateToken(authToken, user)) {
Expand All @@ -80,7 +92,5 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
.setAuthentication(authentication);
}
}

chain.doFilter(request, response);
}
}

0 comments on commit 7d6b155

Please sign in to comment.