1 package net.sumaris.server.http.security;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 import org.apache.commons.lang3.StringUtils;
26 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
27 import org.springframework.security.core.Authentication;
28 import org.springframework.security.core.AuthenticationException;
29 import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
30 import org.springframework.security.web.util.matcher.RequestMatcher;
31
32 import javax.servlet.FilterChain;
33 import javax.servlet.ServletException;
34 import javax.servlet.http.HttpServletRequest;
35 import javax.servlet.http.HttpServletResponse;
36 import java.io.IOException;
37
38 import static java.util.Optional.ofNullable;
39 import static org.apache.commons.lang3.StringUtils.removeStart;
40 import static org.springframework.http.HttpHeaders.AUTHORIZATION;
41
42
43
44
45 public class TokenAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
46
47 private static final String TOKEN = "token";
48
49 protected TokenAuthenticationFilter(RequestMatcher requiresAuthenticationRequestMatcher) {
50 super(requiresAuthenticationRequestMatcher);
51 }
52
53 @Override
54 public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
55
56 final String param = ofNullable(request.getHeader(AUTHORIZATION))
57 .orElse(request.getParameter("t"));
58
59 final String token = ofNullable(param)
60 .map(value -> removeStart(value, TOKEN))
61 .map(StringUtils::trimToNull)
62 .orElse(AnonymousUser.TOKEN);
63
64 final Authentication auth = new UsernamePasswordAuthenticationToken(token, token);
65 return getAuthenticationManager().authenticate(auth);
66 }
67
68 @Override
69 protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
70 super.successfulAuthentication(request, response, chain, authResult);
71 chain.doFilter(request, response);
72 }
73 }