Autenticação JWT com Spring boot
13/06/2018 13:20
0
Boa tarde estou com um problema na liberação de rotas para minha aplicação feita com Spring boot. O problema é que a rota principal "/HOME" pede o token JWT para acessa-la, porem ela está configurada para permitir qualquer tipo de request de qualquer usuário, com ou sem token. Alguém já teve esse tipo de problema ?

Estava seguindo este tutorial: http://andreybleme.com/2017-04-01/autenticacao-com-jwt-no-spring-boot/

Arquivo de boot:

?package br.com.teste;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
@EnableAutoConfiguration
public class Boot
{

public static void main(String[] args)
{
SpringApplication.run(Boot.class, args);
}

@GetMapping("/home")
public String home()
{
return "home";
}
}


Arquivo de configuração:

package br.com.security;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf().disable().authorizeRequests()
.antMatchers("/home").permitAll()
.antMatchers(HttpMethod.POST, "/login").permitAll()
.anyRequest().authenticated()
.and()

// filtra requisições de login
.addFilterBefore(new JWTLoginFilter("/login", authenticationManager()),
UsernamePasswordAuthenticationFilter.class)

// filtra outras requisições para verificar a presença do JWT no header
.addFilterBefore(new JWTAuthenticationFilter(),
UsernamePasswordAuthenticationFilter.class);
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// cria uma conta default
auth.inMemoryAuthentication()
.withUser("admin")
.password("password")
.roles("ADMIN");
}
}?

Arquivo TokenAuthenticationService:


import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class TokenAuthenticationService {

// EXPIRATION_TIME = 10 dias
static final long EXPIRATION_TIME = 860_000_000;
static final String SECRET = "9FFE05B4553F32356D4D70F128FF0BB8C19F64275C45153EF26ED127E264A2AA";
static final String TOKEN_PREFIX = "Bearer";
static final String HEADER_STRING = "Authorization";

static void addAuthentication(HttpServletResponse response, String username) {
String JWT = Jwts.builder()
.setSubject(username)
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
.signWith(SignatureAlgorithm.HS512, SECRET)
.compact();

response.addHeader(HEADER_STRING, TOKEN_PREFIX + " " + JWT);
}

static Authentication getAuthentication(HttpServletRequest request) {
String token = request.getHeader(HEADER_STRING);

if (token != null) {
// faz parse do token
String user = Jwts.parser()
.setSigningKey(SECRET)
.parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
.getBody()
.getSubject();

if (user != null) {
return new UsernamePasswordAuthenticationToken(user, null, Collections.emptyList());
}
}
return null;
}

}


Arquivo JWTLoginFilter:

package br.com.security;

import java.io.IOException;
import java.util.Collections;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.models.AccountCredentials;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import com.fasterxml.jackson.databind.ObjectMapper;

public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter {

protected JWTLoginFilter(String url, AuthenticationManager authManager) {
super(new AntPathRequestMatcher(url));
setAuthenticationManager(authManager);
}

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException, IOException {

AccountCredentials credentials = new ObjectMapper()
.readValue(request.getInputStream(), AccountCredentials.class);

return getAuthenticationManager().authenticate(
new UsernamePasswordAuthenticationToken(
credentials.getUsername(),
credentials.getPassword(),
Collections.emptyList()
)
);
}

@Override
protected void successfulAuthentication(
HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain,
Authentication auth) {

TokenAuthenticationService.addAuthentication(response, auth.getName());
}

}

Arquivo JWTAuthenticationFilter:


package br.com.security;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;

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);
}

}?
Tags: Spring boot, JWT, REST, API


Ainda não faz parte da comunidade???

Para se registrar, clique aqui.


Aprenda Groovy e Grails, Spring e mais com a Formação itexto!

Livro de Spring


Participe do grupo "Spring Brasil" no WhatsApp!
Clique aqui para entrar!


/dev/All

Os melhores blogs de TI
em um único lugar!

 
Spring Brasil é mantido por itexto Consultoria.
Em caso de problemas contacte Henrique Lobo Weissmann (Kico) por e-mail: kico@itexto.com.br
Todo o conteúdo presente neste site adota o Creative Commons como licença padrão.