Good afternoon I have a problem in the release of routes for my application made with Spring boot. The problem is that the main route "/ home" requests the JWT token to access it, but it is configured to allow any kind of request from any user, with or without a token. Has anyone ever had this kind of problem?
I was following this tutorial: link
Boot file:
@SpringBootApplication
@RestController
@EnableAutoConfiguration
public class Boot
{
public static void main(String[] args)
{
SpringApplication.run(Boot.class, args);
}
@GetMapping("/home")
public String home()
{
return "home";
}
}
Configuration file:
@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");
}
}
TokenAuthenticationService file:
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;
}
}
JWTLoginFilter file:
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());
}
}
JWTAuthenticationFilter file:
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);
}
}