I want to consume my api rest from Spirng in Vue.js but I never get the api rest the JWT that I sent from VUE.JS.
They have some idea because this is generated.
Here I leave my spring boot java code:
public class AccountCredentials {
private String username;
private String password;
// getters & setters
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
public class JWTAuthenticationFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain filterChain)
throws IOException, ServletException {
Authentication authentication = TokenAuthenticationService.getAuthentication((HttpServletRequest)request);
SecurityContextHolder.getContext().setAuthentication(authentication);
filterChain.doFilter(request,response);
}
}
public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter {
public JWTLoginFilter(String url, AuthenticationManager authManager) {
super(new AntPathRequestMatcher(url));
setAuthenticationManager(authManager);
}
@Override
public Authentication attemptAuthentication(
HttpServletRequest req, HttpServletResponse res)
throws AuthenticationException, IOException, ServletException {
AccountCredentials creds = new ObjectMapper()
.readValue(req.getInputStream(), AccountCredentials.class);
return getAuthenticationManager().authenticate(
new UsernamePasswordAuthenticationToken(
creds.getUsername(),
ClavePass.Encriptar(creds.getPassword()),
Collections.emptyList()
)
);
}
@Override
protected void successfulAuthentication(
HttpServletRequest req,
HttpServletResponse res, FilterChain chain,
Authentication auth) throws IOException, ServletException {
TokenAuthenticationService
.addAuthentication(res, auth.getName());
}
}
class TokenAuthenticationService {
static final long EXPIRATIONTIME = 864_000_000; // 10 days
static final String SECRET = "ThisIsASecret";
static final String TOKEN_PREFIX = "Bearer";
static final String HEADER_STRING = "Authorization";
static void addAuthentication(HttpServletResponse res, String username) {
String token = Jwts.builder()
.setSubject(username)
// Vamos a asignar un tiempo de expiracion de 1 minuto
// solo con fines demostrativos en el video que hay al final
.setExpiration(new Date(System.currentTimeMillis() + 60000))
// Hash con el que firmaremos la clave
.signWith(SignatureAlgorithm.HS512, "nisira")
.compact();
//agregamos al encabezado el token
res.addHeader("Authorization", "Bearer " + token);
}
static Authentication getAuthentication(HttpServletRequest request) {
String token = request.getHeader("Authorization");
// si hay un token presente, entonces lo validamos
if (token != null) {
String user = Jwts.parser()
.setSigningKey("P@tit0")
.parseClaimsJws(token.replace("Bearer", "")) //este metodo es el que valida
.getBody()
.getSubject();
// Recordamos que para las demás peticiones que no sean /login
// no requerimos una autenticacion por username/password
// por este motivo podemos devolver un UsernamePasswordAuthenticationToken sin password
return user != null ?
new UsernamePasswordAuthenticationToken(user, null, emptyList()) :
null;
}
return null;
}
}
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private IUsuarioService usuarioService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers(HttpMethod.POST, "/login").permitAll()
.anyRequest().authenticated()
.and()
// // We filter the api/login requests
.addFilterBefore(new JWTLoginFilter("/login", authenticationManager()),
UsernamePasswordAuthenticationFilter.class)
// And filter other requests to check the presence of JWT in header
.addFilterBefore(new JWTAuthenticationFilter(),
UsernamePasswordAuthenticationFilter.class);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// Create a default account
Usuario usuario = usuarioService.findAll().stream().filter(U -> U.getIdusuario().trim().equals("ADMINISTRADOR")).findFirst().orElse(null);
auth.inMemoryAuthentication()
.withUser(usuario.getIdusuario().trim())
.password(usuario.getPassword())
.roles("ADMIN");
}
}
This is my Vue.js code with which I consume that api:
this.axios.get('http://localhost:8080/api/teatro', {
headers: {
'Content-Type' : 'application/json',
'Authorization': 'Bearer ' + 'hola'
}
})
When it comes to the method:
@Override
public Authentication attemptAuthentication(
HttpServletRequest req, HttpServletResponse res)
throws AuthenticationException, IOException, ServletException {
AccountCredentials creds = new ObjectMapper ()
.readValue(req.getInputStream(), AccountCredentials.class);
return getAuthenticationManager().authenticate(
new UsernamePasswordAuthenticationToken(
creds.getUsername(),
ClavePass.Encriptar(creds.getPassword()),
Collections.emptyList()
)
);
}
I search if the JWT arrives, it never arrives but when I send it from postman yes, I do not know if it has to be added to the spring boot or vue.js so that the parameters can arrive.