#spring #request #jwt
#весна #запрос #агентство jwt
Вопрос:
Я разрабатываю api в spring boot, JWT и spring security, токен, который я отправляю в json тела, но когда я читаю тело запроса с ним, выдает мне ошибку в почтальоне: Отсутствует требуемое тело запроса: общедоступная организация.springframework.http.ResponseEntity. Не могли бы вы мне помочь, пожалуйста??
Это мое приложение SpringBootApplication:
@SpringBootApplication public class JwtApplication { public static void main(String[] args) { SpringApplication.run(JwtApplication.class, args); } @EnableWebSecurity @Configuration class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .addFilterAfter(new JWTAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class) .authorizeRequests().antMatchers(HttpMethod.POST, "/user").permitAll() .antMatchers(HttpMethod.POST, "/Autenticacion").permitAll().anyRequest().authenticated(); } } }
это мой фильтр:
public class JWTAuthorizationFilter extends OncePerRequestFilter { private final String HEADER = "Authorization"; private final String SESSION = "sesion"; private final String PREFIX = "Bearer "; private final String SECRET = "mySecretKey"; public static final long EXPIRATION_TIME = 900_000; // 15 mins @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; try { boolean resultado_checktoken = checkJWTToken(httpRequest, httpResponse); if (resultado_checktoken) { Claims claims = validateToken(request); if (claims.get("authorities") != null) { setUpSpringAuthentication(claims); } else { SecurityContextHolder.clearContext(); } } else { SecurityContextHolder.clearContext(); } chain.doFilter(request, response); } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException e) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage()); return; } System.out.println("supuestamente no hubo problemas"); } private Claims validateToken(HttpServletRequest request) { //String jwtToken = request.getHeader(HEADER).replace(PREFIX, ""); String jwtToken=""; try { jwtToken = this.getBodySession(request); } catch (IOException e) { e.printStackTrace(); }; return Jwts.parser().setSigningKey(SECRET.getBytes()).parseClaimsJws(jwtToken).getBody(); } /** * Authentication method in Spring flow * * @param claims */ private void setUpSpringAuthentication(Claims claims) { @SuppressWarnings("unchecked") Listlt;Stringgt; authorities = (Listlt;Stringgt;) claims.get("authorities"); UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(claims.getSubject(), null, authorities.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList())); SecurityContextHolder.getContext().setAuthentication(auth); } private boolean checkJWTToken(HttpServletRequest request, HttpServletResponse res) throws IOException { String authenticationHeader = ""; authenticationHeader = this.getBodySession(request); if (authenticationHeader == null || !authenticationHeader.startsWith(PREFIX)) return false; return true; } public String getBodySession(HttpServletRequest request) throws IOException { String sbody = ""; HttpServletRequest servletRequest = new ContentCachingRequestWrapper(request); //servletRequest.getParameterMap(); sbody = servletRequest.getReader().lines().collect(Collectors.joining()); String Field = SESSION; String scampo = ""; if (sbody.contains(Field)) { scampo = sbody.substring(sbody.indexOf(Field), sbody.indexOf("n", sbody.indexOf(Field))) .replace(Field "": "", "").replace(""", "").replace(",", ""); } System.out.println("sbody: " sbody " sesion: " scampo); return scampo; } public String getBodySession_2021_11_23(HttpServletRequest request) throws IOException { String body = null; StringBuilder stringBuilder = new StringBuilder(); BufferedReader bufferedReader = null; try { InputStream inputStream = request.getInputStream(); if (inputStream != null) { bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); char[] charBuffer = new char[128]; int bytesRead = -1; while ((bytesRead = bufferedReader.read(charBuffer)) gt; 0) { stringBuilder.append(charBuffer, 0, bytesRead); } } else { stringBuilder.append(""); } body = stringBuilder.toString(); String Field = "sesion"; String scampo = ""; if (body.contains(Field)) { scampo = body.substring(body.indexOf(Field), body.indexOf("n", body.indexOf(Field))) .replace(Field "": "", "").replace(""", "").replace(",", ""); } System.out.println("sbody: " body " sesion: " scampo); return scampo; } catch (IOException ex) { throw ex; } }
Комментарии:
1. Что вы пытаетесь сделать с помощью почтальона? пожалуйста, опубликуйте более подробную информацию о запросах, которые завершились неудачей.