Skip to content

Commit

Permalink
Improve security and performance
Browse files Browse the repository at this point in the history
  • Loading branch information
leonardo2204 authored and murraco committed May 29, 2020
1 parent fefc24b commit a585e26
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 10 deletions.
19 changes: 10 additions & 9 deletions src/main/java/murraco/security/JwtTokenFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@
import org.springframework.web.filter.GenericFilterBean;

import murraco.exception.CustomException;
import org.springframework.web.filter.OncePerRequestFilter;

public class JwtTokenFilter extends GenericFilterBean {
//we should use OncePerRequestFilter since we are doing a database call, there is no point in doing this more than once
public class JwtTokenFilter extends OncePerRequestFilter {

private JwtTokenProvider jwtTokenProvider;

Expand All @@ -24,22 +26,21 @@ public JwtTokenFilter(JwtTokenProvider jwtTokenProvider) {
}

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
throws IOException, ServletException {

String token = jwtTokenProvider.resolveToken((HttpServletRequest) req);
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
String token = jwtTokenProvider.resolveToken(httpServletRequest);
try {
if (token != null && jwtTokenProvider.validateToken(token)) {
Authentication auth = token != null ? jwtTokenProvider.getAuthentication(token) : null;
Authentication auth = jwtTokenProvider.getAuthentication(token);
SecurityContextHolder.getContext().setAuthentication(auth);
}
} catch (CustomException ex) {
HttpServletResponse response = (HttpServletResponse) res;
response.sendError(ex.getHttpStatus().value(), ex.getMessage());
//this is very important, since it guarantees the user is not authenticated at all
SecurityContextHolder.clearContext();
httpServletResponse.sendError(ex.getHttpStatus().value(), ex.getMessage());
return;
}

filterChain.doFilter(req, res);
filterChain.doFilter(httpServletRequest, httpServletResponse);
}

}
2 changes: 1 addition & 1 deletion src/main/java/murraco/security/JwtTokenProvider.java
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public String getUsername(String token) {
public String resolveToken(HttpServletRequest req) {
String bearerToken = req.getHeader("Authorization");
if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring(7, bearerToken.length());
return bearerToken.substring(7);
}
return null;
}
Expand Down

0 comments on commit a585e26

Please sign in to comment.