Untitled
unknown
plain_text
a month ago
2.3 kB
2
Indexable
Never
package com.prueba.marvelapi.security.filter; import com.fasterxml.jackson.databind.ObjectMapper; import com.prueba.marvelapi.security.TokenUtils; import com.prueba.marvelapi.security.UserDetailsImpl; import com.prueba.marvelapi.security.dto.AuthCredentials; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import java.io.IOException; import java.util.Collections; public class JWTAutenticationFilter extends UsernamePasswordAuthenticationFilter { @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { AuthCredentials authCredentials = new AuthCredentials(); try { authCredentials = new ObjectMapper().readValue(request.getReader(), AuthCredentials.class); }catch (IOException e){ e.printStackTrace(); } UsernamePasswordAuthenticationToken usernamePAT = new UsernamePasswordAuthenticationToken( authCredentials.getUsername(), authCredentials.getPassword(), Collections.emptyList() ); return getAuthenticationManager().authenticate(usernamePAT); } @Override protected void successfulAuthentication( HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException{ UserDetailsImpl userDetails = (UserDetailsImpl) authResult.getPrincipal(); String token = TokenUtils.createToken(userDetails.getUsername(),userDetails.getName()); response.addHeader("Authorization", "Bearer " + token); response.getWriter().flush(); super.successfulAuthentication(request,response ,chain,authResult); } }