Boa tarde, profile não rolou e foi deletado o dado (deve bloquear e mostrar mensagem de erro)
@EnableWebSecurity
@Configuration
@Profile({"qa", "prod","test"})
public class SecurityConfigurations extends WebSecurityConfigurerAdapter {
.
.
.
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(HttpMethod.POST,"/auth").permitAll()
.antMatchers(HttpMethod.GET,"/actuator/**").permitAll()
.antMatchers(HttpMethod.DELETE,"/event/*").hasRole("MODERATOR")
.anyRequest().authenticated()
.and().csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().addFilterBefore(new AuthenticationTokenFilter(tokenService, userRepository),
UsernamePasswordAuthenticationFilter.class);
}
@AllArgsConstructor
public class AuthenticationTokenFilter extends OncePerRequestFilter {
private TokenService tokenService;
private UserRepository userRepository;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String token = restoreToken(request);
boolean validated = tokenService.isTokenValidated(token);
if (validated){
authenticateClient(token);
}
filterChain.doFilter(request,response);
}
private void authenticateClient(String token) {
String userId = tokenService.getUserId(token);
User user = userRepository.findById(userId).get();
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user,
null, user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
}
private String restoreToken(HttpServletRequest httpServletRequest) {
String token = httpServletRequest.getHeader("Authorization");
if (token == null || token.isEmpty() || !token.startsWith("Bearer ")) {
return null;
}
return token.substring(7, token.length());
}
}
Token Service
@Service
public class TokenService {
@Value("${security.jwt.expiration}")
private String expiration;
@Value("${security.jwt.secret}")
private String secret;
public String getToken(Authentication authentication){
User user = (User) authentication.getPrincipal();
Date now = new Date();
Date dateExpiration = new Date(now.getTime() + Long.parseLong(expiration));
return Jwts.builder().setIssuer("GO-SPORTS")
.setSubject(user.getId())
.setIssuedAt(now)
.setExpiration(dateExpiration)
.signWith(SignatureAlgorithm.HS256,secret)
.compact();
}
public String getUserId(String token) {
Claims claims = Jwts.parser().setSigningKey(this.secret).parseClaimsJws(token).getBody();
return claims.getSubject().toString();
}
public boolean isTokenValidated(String token){
try {
Jwts.parser().setSigningKey(this.secret).parseClaimsJws(token);
return true;
} catch (Exception e){
return false;
}
}
}
Tentei deletar mas não rolou a mostrar mensagem de erro que role não é permitido. Se quiser dá uma olhada o complexo código no meu repositório e criei o PR, seguinte: https://github.com/jsnpereira/go-sports-backend/pull/7
Espero que me ajudar esse problema.