· 4 years ago · Nov 25, 2020, 12:08 PM
1public class JwtAuthUsernameAndPassword extends UsernamePasswordAuthenticationFilter {
2
3 private final AuthenticationManager authenticationManager;
4 private final SecretKey secretKey;
5
6 public JwtAuthUsernameAndPassword(AuthenticationManager authenticationManager, SecretKey secretKey) {
7 this.authenticationManager = authenticationManager;
8 this.secretKey = secretKey;
9 }
10
11 // JWT STEP 1 LOGIN AUTHENTICATION
12
13 @Override
14 public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
15 throws AuthenticationException {
16
17 System.out.println();
18
19 try {
20 UserBindingModel authUserRequest = new ObjectMapper().readValue(request.getInputStream(),
21 UserBindingModel.class);
22
23 Authentication authentication = new UsernamePasswordAuthenticationToken(
24 authUserRequest.getUsername(),
25 authUserRequest.getPassword());
26
27 //System.out.println(this.authenticationManager.authenticate(authentication));
28
29 Authentication authenticateResult = this.authenticationManager.authenticate(authentication);
30 return authenticateResult;
31
32 } catch (IOException e) {
33 throw new RuntimeException(e);
34 }
35 }
36
37 // JWT STEP2 LOGIN
38 @Override
39 protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
40 Authentication authResult) throws IOException, ServletException {
41
42 String token = Jwts.builder().setSubject(authResult.getName()).claim("authorities", authResult.getAuthorities())
43 .setIssuedAt(new Date())
44 .setExpiration(java.sql.Date.valueOf(LocalDate.now().plusDays(JwtConstant.TOKEN_EXPIRATION_AFTER_DAYS)))
45 .signWith(this.secretKey).compact();
46
47 response.addHeader(JwtConstant.AUTHORIZATION_HEADER, JwtConstant.TOKEN_PREFIX + token);
48 }
49}