20
respostas

400 Bad Request

Quando fiz a requisição retornou 400 bad request e não retornou nada.

20 respostas

Olá, João!

Parabéns pela dedicação!

Esse tipo de erro ocorre devido a uma requisição mal formulada, ou seja, provavelmente tem algum erro em seu código. Revise as aulas, e se mesmo asim não encontrar o erro, tente baixar o projeto que o professor disponibiliza no começo do próximo capítulo.

Espero ter ajudado!

Boa sorte em seus estudos!

The method signWith(SignatureAlgorithm, String) from the type JwtBuilder is deprecated esse método se encontra depreciado na minha api.

Olá, João!

Realmente o método está depreciado.

Confira na documentação as alternativas para esse método: https://javadoc.io/static/io.jsonwebtoken/jjwt-api/0.11.2/io/jsonwebtoken/JwtBuilder.html#signWith(io.jsonwebtoken.SignatureAlgorithm,%20java.lang.String)

Se tiver alguma dificuldade, nos avise.

public String gerarToken(Authentication authentication) {

     UsuarioModel logado = (UsuarioModel) authentication.getPrincipal();
    Date hoje = new Date();
    Date dataExpiracao = new Date(hoje.getTime() + Long.parseLong(expiration));
    byte[] keyBytes = Decoders.BASE64.decode(secret);
    Key key = Keys.hmacShaKeyFor(keyBytes);
    JwtBuilder.signWith(SignatureAlgorithm.HS256);
    return Jwts.builder()
           .setIssuer("API-SRQSYSFENIX")
           .setSubject(Integer.valueOf(logado.getUsuarioId()).toString())
           .setIssuedAt(hoje)
           .setExpiration(dataExpiracao)
           .compact();

        }

    }

The method signWith(Key) in the type JwtBuilder is not applicable for the arguments (SignatureAlgorithm)Java(67108979) agora está mostrando esse erro

Olhei a documentação tentei implementar, mas ainda não deu certo

Apareceu esse erro do meu console quando tento executar a requisição. 2022-07-19 14:47:47.192 INFO 15092 --- [on(1)-127.0.0.1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet' 2022-07-19 14:47:47.192 INFO 15092 --- [on(1)-127.0.0.1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet' 2022-07-19 14:47:47.319 INFO 15092 --- [on(1)-127.0.0.1] o.s.b.a.e.web.EndpointLinksResolver : Exposing 1 endpoint(s) beneath base path '/actuator' 2022-07-19 14:47:47.393 INFO 15092 --- [on(1)-127.0.0.1] o.s.web.servlet.DispatcherServlet : Completed initialization in 200 ms 2022-07-19 14:47:47.729 INFO 15092 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729 2022-07-19 14:47:47.829 INFO 15092 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' 2022-07-19 14:47:47.847 INFO 15092 --- [ restartedMain] c.s.a.ForumApiApplication : Started ForumApiApplication in 12.366 seconds (JVM running for 13.748) 2022-07-19 14:49:56.281 WARN 15092 --- [nio-8080-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 208, SQLState: S0002 2022-07-19 14:49:56.283 ERROR 15092 --- [nio-8080-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper : Invalid object name 'Usuarios UsuariosCategorias'.

Oi João,

Veja se consegue postar aqui o log completo do servidor.

. __ _ __ _ _ /\ / _'_ _ _ _()_ _ __ _ \ \ \ ( ( )___ | ' | '| | ' / ` | \ \ \ \/ ___)| |)| | | | | || (| | ) ) ) ) ' |__| .|| ||_| |_, | / / / / =========||==============|__/=//// :: Spring Boot :: (v2.5.6)

2022-07-19 16:29:43.260 INFO 13160 --- [ restartedMain] c.s.a.ApiSrqsysfenixApplication : Starting ApiSrqsysfenixApplication using Java 17.0.1 on NB110112 with PID 13160 (C:\Users\joao.pereira\Documents\forum started by joao.pereira in C:\Users\joao.pereira\Documents\forum) 2022-07-19 16:29:43.264 INFO 13160 --- [ restartedMain] c.s.a.ForumApi : No active profile set, falling back to default profiles: default 2022-07-19 16:29:43.370 INFO 13160 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable 2022-07-19 16:29:43.387 INFO 13160 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG' 2022-07-19 16:29:44.664 INFO 13160 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode. 2022-07-19 16:29:44.739 INFO 13160 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 62 ms. Found 1 JPA repository interfaces. 2022-07-19 16:29:44.740 INFO 13160 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode. 2022-07-19 16:29:44.753 INFO 13160 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 11 ms. Found 2 JPA repository interfaces. 2022-07-19 16:29:46.918 INFO 13160 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) 2022-07-19 16:29:46.932 INFO 13160 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2022-07-19 16:29:46.933 INFO 13160 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.54] 2022-07-19 16:29:47.133 INFO 13160 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2022-07-19 16:29:47.134 INFO 13160 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 3745 ms 2022-07-19 16:29:47.907 INFO 13160 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default] 2022-07-19 16:29:48.019 INFO 13160 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.32.Final 2022-07-19 16:29:48.248 INFO 13160 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final} 2022-07-19 16:29:48.526 INFO 13160 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting... 2022-07-19 16:29:49.036 INFO 13160 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed. 2022-07-19 16:29:49.090 INFO 13160 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.SQLServer2012Dialect 2022-07-19 16:29:52.224 INFO 13160 --- [ restartedMain] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform] 2022-07-19 16:29:52.242 INFO 13160 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default' 2022-07-19 16:29:52.277 INFO 13160 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default] 2022-07-19 16:29:52.356 INFO 13160 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-2 - Starting... 2022-07-19 16:29:52.411 INFO 13160 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-2 - Start completed. 2022-07-19 16:29:52.417 INFO 13160 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.SQLServer2012Dialect 2022-07-19 16:29:52.671 INFO 13160 --- [ restartedMain] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]

2022-07-19 16:29:52.673 INFO 13160 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default' 2022-07-19 16:29:53.344 WARN 13160 --- [ restartedMain] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning 2022-07-19 16:29:54.072 INFO 13160 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Will secure any request with [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@4ecee6e6, org.springframework.security.web.context.SecurityContextPersistenceFilter@46d2eac6, org.springframework.security.web.header.HeaderWriterFilter@1d4f14b3, org.springframework.security.web.authentication.logout.LogoutFilter@fa3f2fa, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@47b36655, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@2bb1f1b0, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@5e58f305, org.springframework.security.web.session.SessionManagementFilter@57656238, org.springframework.security.web.access.ExceptionTranslationFilter@2fe544c, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@384942d1] 2022-07-19 16:29:56.333 INFO 13160 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729 2022-07-19 16:29:56.360 INFO 13160 --- [ restartedMain] o.s.b.a.e.web.EndpointLinksResolver : Exposing 1 endpoint(s) beneath base path '/actuator'2022-07-19 16:29:56.546 INFO 13160 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' 2022-07-19 16:29:56.658 INFO 13160 --- [ restartedMain] c.s.a.ForumApi : Started ForumApi in 14.096 seconds (JVM running for 15.309) 2022-07-19 16:29:57.591 INFO 13160 --- [on(2)-127.0.0.1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet' 2022-07-19 16:29:57.594 INFO 13160 --- [on(2)-127.0.0.1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet' 2022-07-19 16:29:57.598 INFO 13160 --- [on(2)-127.0.0.1] o.s.web.servlet.DispatcherServlet : Completed initialization in 3 ms 2022-07-19 16:30:20.579 WARN 13160 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 208, SQLState: S0002 2022-07-19 16:30:20.582 ERROR 13160 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : Invalid object name 'Usuarios UsuariosCategorias'

Insira aqui a descrição dessa imagem para ajudar na acessibilidade

Olá, João!

Na chamada no método signWith(), tente adicionar a chave como parâmetro:

JwtBuilder.signWith(key, SignatureAlgorithm.HS256);

Nos diga se funcionou.

  public String gerarToken(Authentication authentication) {
    UsuarioModel logado = (UsuarioModel) authentication.getPrincipal();
    Date hoje = new Date();
    Date dataExpiracao = new Date(hoje.getTime() + Long.parseLong(expiration));
    return Jwts.builder()
           .setIssuer("API-FORUM")
           .setSubject(Integer.valueOf(logado.getUsuarioId()).toString())
           .setIssuedAt(hoje)
           .setExpiration(dataExpiracao)
           .signWith(SignatureAlgorithm.HS256, secret)<= substituindo aqui?
           .compact();

        }

    }

Vou postar o código pra não haver confusão. Se atente à ordem dos parâmetros, a chave deve vir primeiro:

public String gerarToken(Authentication authentication) {
    UsuarioModel logado = (UsuarioModel) authentication.getPrincipal();
    Date hoje = new Date();
    Date dataExpiracao = new Date(hoje.getTime() + Long.parseLong(expiration));
    byte[] keyBytes = Decoders.BASE64.decode(secret);
    Key key = Keys.hmacShaKeyFor(keyBytes);
    JwtBuilder.signWith(key, SignatureAlgorithm.HS256);
    return Jwts.builder()
           .setIssuer("API-SRQSYSFENIX")
           .setSubject(Integer.valueOf(logado.getUsuarioId()).toString())
           .setIssuedAt(hoje)
           .setExpiration(dataExpiracao)
           .compact();

        }

}

Com base no último erro qur você postou ("The method signWith(Key) in the type JwtBuilder is not applicable for the arguments"), você também pode tentar passando somente a chave, sem o algoritmo:

public String gerarToken(Authentication authentication) {
UsuarioModel logado = (UsuarioModel) authentication.getPrincipal();
Date hoje = new Date();
Date dataExpiracao = new Date(hoje.getTime() + Long.parseLong(expiration));
byte[] keyBytes = Decoders.BASE64.decode(secret);
Key key = Keys.hmacShaKeyFor(keyBytes);
JwtBuilder.signWith(key);
return Jwts.builder()
       .setIssuer("API-SRQSYSFENIX")
       .setSubject(Integer.valueOf(logado.getUsuarioId()).toString())
       .setIssuedAt(hoje)
       .setExpiration(dataExpiracao)
       .compact();

    }

}

Esse erro que está "estranho": Invalid object name 'Usuarios UsuariosCategorias'

Posta aqui o código das suas classes: AutenticacaoController, AutenticacaoService, Usuario e SecurityConfigurations.

public String gerarToken(Authentication authentication) {
    UsuarioModel logado = (UsuarioModel) authentication.getPrincipal();
    Date hoje = new Date();
    Date dataExpiracao = new Date(hoje.getTime() + Long.parseLong(expiration));
    byte[] keyBytes = Decoders.BASE64.decode(secret);
    Key key = Keys.hmacShaKeyFor(keyBytes);
    JwtBuilder.signWith(key, SignatureAlgorithm.HS256);
    return Jwts.builder()
           .setIssuer("API-SRQSYSFENIX")
           .setSubject(Integer.valueOf(logado.getUsuarioId()).toString())
           .setIssuedAt(hoje)
           .setExpiration(dataExpiracao)
           .compact();

        }

}

Apareceu esse erro: Cannot make a static reference to the non-static method signWith(Key, SignatureAlgorithm) from the type JwtBuilder

io.jsonwebtoken jjwt-api 0.11.2 Essa dependência está correta?

João, eu dei uma olhada na aula onde o código foi desenvolvido pelo professor, e o motivo da confusão pode ter sido porque eu me baseei no primeiro código que você postou, que está diferente do código do instrutor.

Acho que assim funciona. Teste aí e nos diga:

public String gerarToken(Authentication authentication) {
UsuarioModel logado = (UsuarioModel) authentication.getPrincipal();
Date hoje = new Date();
Date dataExpiracao = new Date(hoje.getTime() + Long.parseLong(expiration));
byte[] keyBytes = Decoders.BASE64.decode(secret);
Key key = Keys.hmacShaKeyFor(keyBytes);
return Jwts.builder()
       .setIssuer("API-FORUM")
       .setSubject(Integer.valueOf(logado.getUsuarioId()).toString())
       .setIssuedAt(hoje)
       .setExpiration(dataExpiracao)
       .signWith(key, SignatureAlgorithm.HS256)<= substituindo aqui?
       .compact();

    }

}

Para a minha API funcionar a autenticação com um banco de dados(sql Server) a tabela de Perfil e a tabela de Usuário precisa ser conectada?

Amigo, nos Postman coloca o e-mail do usuário e senha (que era pra ser "1,2,3,4,5,6") que está no banco de dados.