@Slf4j public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter { private UserService userService; private Environment env;
public AuthenticationFilter(AuthenticationManager authenticationManager, UserService userService, Environment env){ super.setAuthenticationManager( authenticationManager); this.userService = userService; this.env = env; }
@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
try { RequestLogin creds = new ObjectMapper().readValue(request.getInputStream(), RequestLogin.class);
Authentication token = new UsernamePasswordAuthenticationToken(creds.getEmail(), creds.getPassword(), new ArrayList<>());
return getAuthenticationManager().authenticate(token); } catch (IOException e){ throw new RuntimeException(e); } }
@Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { String username = ((User)authResult.getPrincipal()).getUsername(); UserDto userDetails = userService.getUserDetailsByEmail(username);
String token = Jwts.builder() .setSubject(userDetails.getUserId()) .setExpiration(new Date(System.currentTimeMillis() + Long.parseLong(env.getProperty("token.expiration_time")))) .signWith(SignatureAlgorithm.HS512, env.getProperty("token.secret")) .compact();
response.addHeader("token", token); response.addHeader("userId", userDetails.getUserId()); } }
|