· 7 years ago · Apr 24, 2018, 08:52 PM
1private final AuthenticationManager authenticationManager;
2 private final PropertyFileText properties;
3
4 public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
5 this.authenticationManager = authenticationManager;
6 properties = new PropertyFileText(this.getClass().getResource("/security.properties").getPath());
7 setUsernameParameter("email");
8 }
9
10 @Override
11 public Authentication attemptAuthentication(HttpServletRequest httpServletRequest,
12 HttpServletResponse httpServletResponse)
13 throws AuthenticationException {
14 try {
15 ObjectMapper objectMapper = new ObjectMapper();
16 AuthenticationCredentials credentials = objectMapper.readValue(httpServletRequest.getInputStream(),
17 AuthenticationCredentials.class);
18
19 return authenticationManager.authenticate(
20 new UsernamePasswordAuthenticationToken(
21 credentials.getEmail(),
22 credentials.getPassword(), emptyList()
23 )
24 );
25 } catch (IOException e) {
26 throw new RuntimeException(e);
27 }
28 }
29
30 @Override
31 protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
32 long expirationTime = Long.valueOf(properties.read("EXPIRATION_TIME"));
33 String secretKey = properties.read("SECRET");
34 String headerString = properties.read("HEADER_STRING");
35 String tokenPrefix = properties.read("TOKEN_PREFIX");
36
37 String token = Jwts.builder()
38 .setSubject(((User) authResult.getPrincipal()).getUsername())
39 .setExpiration(new Date(System.currentTimeMillis() + expirationTime))
40 .signWith(SignatureAlgorithm.HS512, secretKey)
41 .compact();
42
43 response.addHeader(headerString, tokenPrefix + token);
44 }