-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtoken_filter.java
More file actions
executable file
·64 lines (50 loc) · 2.32 KB
/
token_filter.java
File metadata and controls
executable file
·64 lines (50 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
@Slf4j
public class JwtAuthenticationTokenFilter extends AbstractAuthenticationProcessingFilter {
public JwtAuthenticationTokenFilter(RequestMatcher requestMatcher) {
super(requestMatcher);
}
/**
* Attempt to authenticate request - basically just pass over to another method to authenticate request headers
*/
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
if(SecurityContextHolder.getContext().getAuthentication() != null){
log.trace("User has been authenticated already, proceeding");
return SecurityContextHolder.getContext().getAuthentication();
}
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith("Bearer ")) {
log.trace("No JWT Token found, redirecting to login");
response.sendRedirect("/api/login");
return null;
}
log.trace("JWT token in the request: {}", header);
// mind the 'BEARER ' string
String authToken = header.substring(7);
if(authToken.startsWith("\"") && authToken.endsWith("\"")){
authToken = authToken.substring(1, authToken.length()-1);
}
authToken = new String(Base64Utils.decodeFromUrlSafeString(authToken), Charset.forName("UTF-8"));
log.trace("Extracted JWT token: {}", authToken);
JwtAuthenticationToken authRequest = new JwtAuthenticationToken(authToken);
return getAuthenticationManager().authenticate(authRequest);
}
/**
* Make sure the rest of the filterchain is satisfied
*
* @param request
* @param response
* @param chain
* @param authResult
* @throws IOException
* @throws ServletException
*/
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult)
throws IOException, ServletException {
super.successfulAuthentication(request, response, chain, authResult);
// As this authentication is in HTTP header, after success we need to continue the request normally
// and return the response as if the resource was not secured at all
chain.doFilter(request, response);
}
}