8
respostas

403 Forbidden

a minha requisição voltou vazia e com o status:403 https://imgur.com/a/g403fmd

8 respostas

Posta aqui como ficou sua classe de configurações de segurança.

package br.com.alura.forum.config.validacao.security;

import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; 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.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import br.com.alura.forum.repository.UsuarioRepository;

@EnableWebSecurity @Configuration public class SecurityConfigurations extends WebSecurityConfigurerAdapter {

@Autowired
private AutenticacaoService autenticacaoService;

@Autowired
private TokenService tokenService;

@Autowired
private UsuarioRepository usuarioRepository;

@Override
@Bean
protected AuthenticationManager authenticationManager() throws Exception {
    return super.authenticationManager();
}

//Configuracoes de autenticacao
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(autenticacaoService).passwordEncoder(new BCryptPasswordEncoder());
}

//Configuracoes de autorizacao
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
    .antMatchers(HttpMethod.GET, "/topicos").permitAll()
    .antMatchers(HttpMethod.GET, "/topicos/*").permitAll()
    .antMatchers(HttpMethod.POST, "/auth").permitAll()
    .anyRequest().authenticated()
    .and().csrf().disable()
    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    .and().addFilterBefore(new AutenticacaoViaTokenFilter(tokenService, usuarioRepository), UsernamePasswordAuthenticationFilter.class);
}


//Configuracoes de recursos estaticos(js, css, imagens, etc.)
@Override
public void configure(WebSecurity web) throws Exception {
}

}

Ta certinho. Posta tambem as classes: AutenticacaoViaTokenFilter e AutenticacaoController.

AutenticacaoViaTokenFilter package br.com.alura.forum.config.validacao.security;

import java.io.IOException;

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

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.filter.OncePerRequestFilter;

import br.com.alura.forum.modelo.Usuario; import br.com.alura.forum.repository.UsuarioRepository;

public class AutenticacaoViaTokenFilter extends OncePerRequestFilter {

private TokenService tokenService;
private UsuarioRepository repository;

public AutenticacaoViaTokenFilter(TokenService tokenService, UsuarioRepository repository) {
    this.tokenService = tokenService;
    this.repository = repository;
} 

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) 
        throws ServletException, IOException {

        String token = recuperarToken(request);
        boolean valido = tokenService.isTokenValido(token);
        if(valido) {
            autenticarCliente(token);
        }


        filterChain.doFilter(request, response);
    } 

private void autenticarCliente(String token) {
    Long idUsuario = tokenService.getIdUsuario(token);
    Usuario usuario = repository.findById(idUsuario).get();
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(usuario, null, usuario.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(authentication);

}

private String recuperarToken(HttpServletRequest request) {
    String token = request.getHeader("Authorization");
    if (token == null || token.isEmpty() || !token.startsWith("Bearer ")) {
        return null;
    }

    return token.substring(7, token.length());
}

}

AutenticacaoController package br.com.alura.forum.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; 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.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;

import br.com.alura.forum.config.validacao.security.TokenService; import br.com.alura.forum.controller.dto.TokenDto; import br.com.alura.forum.controller.form.LoginForm;

@RestController @RequestMapping("/auth") public class AutenticacaoController {

@Autowired
private AuthenticationManager authManager;
@Autowired

private TokenService tokenService;
@PostMapping

public ResponseEntity<TokenDto> autenticar(@RequestBody @Valid LoginForm form) {
    UsernamePasswordAuthenticationToken dadosLogin = form.converter();

    try {
        Authentication authentication = authManager.authenticate(dadosLogin);
        String token = tokenService.gerarToken(authentication);
        return ResponseEntity.ok(new TokenDto(token, "Bearer"));
    } catch (AuthenticationException e) {
        return ResponseEntity.badRequest().build();
    }
}

}

Tudo ok também. Coloca um printstacktrace no try catch do controller:

 } catch (AuthenticationException e) {
     e.printStackTrace();
    return ResponseEntity.badRequest().build();
}

E quando se autenticar veja no console a Exception que ocorreu.

09:45:07.769 [Thread-0] DEBUG org.springframework.boot.devtools.restart.classloader.RestartClassLoader - Created RestartClassLoader org.springframework.boot.devtools.restart.classloader.RestartClassLoader@40019fe1

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

2022-05-27 09:45:08.335 INFO 9324 --- [ restartedMain] br.com.alura.forum.ForumApplication : Starting ForumApplication using Java 18 on NB110112 with PID 9324 (C:\Users\joao.pereira\Documents\forum\forum\target\classes started by joao.pereira in c:\Users\joao.pereira\Documents\forum\forum) 2022-05-27 09:45:08.337 INFO 9324 --- [ restartedMain] br.com.alura.forum.ForumApplication : No active profile set, falling back to 1 default profile: "default" 2022-05-27 09:45:08.469 INFO 9324 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable 2022-05-27 09:45:08.470 INFO 9324 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG' 2022-05-27 09:45:10.073 INFO 9324 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode. 2022-05-27 09:45:10.202 INFO 9324 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 109 ms. Found 3 JPA repository interfaces. 2022-05-27 09:45:11.552 INFO 9324 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) 2022-05-27 09:45:11.571 INFO 9324 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2022-05-27 09:45:11.572 INFO 9324 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.60] 2022-05-27 09:45:11.728 INFO 9324 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2022-05-27 09:45:11.729 INFO 9324 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 3257 ms 2022-05-27 09:45:11.795 INFO 9324 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting... 2022-05-27 09:45:12.049 INFO 9324 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed. 2022-05-27 09:45:12.073 INFO 9324 --- [ restartedMain] o.s.b.a.h2.H2ConsoleAutoConfiguration : H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:alura-forum' 2022-05-27 09:45:12.345 INFO 9324 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default] 2022-05-27 09:45:12.472 INFO 9324 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.7.Final 2022-05-27 09:45:12.778 INFO 9324 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final} 2022-05-27 09:45:13.005 INFO 9324 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect Hibernate: create table curso ( id bigint generated by default as identity, categoria varchar(255), nome varchar(255), primary key (id) ) Hibernate:

create table perfil (
   id bigint generated by default as identity,
    nome varchar(255),
    primary key (id)
)

Hibernate:

create table resposta (
   id bigint generated by default as identity,
    data_criacao timestamp,
    mensagem varchar(255),
    solucao boolean,
    autor_id bigint,
    topico_id bigint,
    primary key (id)
)

Hibernate:

create table topico (
   id bigint generated by default as identity,
    data_criacao timestamp,
    mensagem varchar(255),
    status varchar(255),
    titulo varchar(255),
    autor_id bigint,
    curso_id bigint,
    primary key (id)
)

Hibernate:

create table usuario (
   id bigint generated by default as identity,
    email varchar(255),
    nome varchar(255),
    senha varchar(255),
    primary key (id)
)

Hibernate:

create table usuario_perfis (
   usuario_id bigint not null,
    perfis_id bigint not null
)

Hibernate:

alter table resposta 
   add constraint FK9999kvnmdq63ah7imctrl06r7 
   foreign key (autor_id) 
   references usuario

Hibernate:

alter table resposta 
   add constraint FKltuv9rkfjtlmn8b0rb3wdbjsv 
   foreign key (topico_id) 
   references topico

Hibernate:

alter table topico 
   add constraint FKsk04hscorwqdymnafg8882v64 
   foreign key (autor_id) 
   references usuario

Hibernate:

alter table topico 
   add constraint FKcaaogjo0ynd54updie6kdpxd1 
   foreign key (curso_id) 
   references curso
   Hibernate: 

alter table usuario_perfis 
   add constraint FK7bhs80brgvo80vhme3u8m6ive 
   foreign key (perfis_id) 
   references perfil

Hibernate:

alter table usuario_perfis 
   add constraint FKs91tgiyagbilt959wbufiphgc 
   foreign key (usuario_id) 
   references usuario

2022-05-27 09:45:14.228 INFO 9324 --- [ restartedMain] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform] 2022-05-27 09:45:14.243 INFO 9324 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default' 2022-05-27 09:45:14.863 WARN 9324 --- [ 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-05-27 09:45:15.338 INFO 9324 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Will not secure any request 2022-05-27 09:45:16.090 INFO 9324 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729 2022-05-27 09:45:16.220 INFO 9324 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' 2022-05-27 09:45:16.252 INFO 9324 --- [ restartedMain] br.com.alura.forum.ForumApplication : Started ForumApplication in 8.463 seconds (JVM running for 9.453) 2022-05-27 10:01:21.817 INFO 9324 --- [nio-8080-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet' 2022-05-27 10:01:21.818 INFO 9324 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet' 2022-05-27 10:01:21.822 INFO 9324 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Completed initialization in 4 ms