Solucionado (ver solução)
Solucionado
(ver solução)
6
respostas

alguem me ajuda com o erro 403

vou por todas as classes relacionadas a usuario, se precisarem de mais coisa é só pedir

classe usuario

package com.example.demo.domain.objeto;

import jakarta.persistence.Id;

import java.util.Collection;
import java.util.List;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Table;
import lombok.EqualsAndHashCode;
import lombok.Getter;

@Table(name="usuario")
@Entity(name="usuario")
@Getter
@EqualsAndHashCode(of = "id")
public class Usuario implements UserDetails {
  
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String login;
    private String senha;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
       return List.of(new SimpleGrantedAuthority("ROLE_USER"));
    }
    @Override
    public String getPassword() {
        return senha;
    }
    @Override
    public String getUsername() {
        return login;
    }

}

classe controlerusuario

package com.example.demo.controler;

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.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 com.example.demo.dados.DadosAutentica;

import jakarta.validation.Valid;
@RestController
@RequestMapping("/usuario")
public class UsuarioControler {
    @Autowired
     private AuthenticationManager manager;

      @PostMapping
    public ResponseEntity efetuarLogin(@RequestBody @Valid DadosAutentica dados) {
        var token = new UsernamePasswordAuthenticationToken(dados.login(), dados.senha());
        var authenticaon = manager.authenticate(token);

        return ResponseEntity.ok().build();
    }
}

classe dadosautentica

package com.example.demo.dados;

public record DadosAutentica (String login, String senha) {
    
}

repository usuario

package com.example.demo.repository;

import org.springframework.data.jpa.repository.JpaRepository;


import com.example.demo.domain.objeto.Usuario;

public interface UsuarioRepositorio extends JpaRepository<Usuario, Long> {
    Usuario findByLogin(String login);
}

authentica service

package com.example.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.example.demo.repository.UsuarioRepositorio;

@Service
public class AutenticaService implements UserDetailsService {
        @Autowired
        private UsuarioRepositorio repository;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return repository.findByLogin(username);
    }
    
}

do db.migrations

create table usuario(
    id bigint not null auto_increment,
    Login varchar(100),
    senha varchar(100),
    
    primary key(id)


);



spring security


6 respostas

Oi!

Manda o código da classe de configurações de segurança.

package com.example.demo.infra.securityconfiguration;

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.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.csrf(csrf -> csrf.disable())
            .authorizeHttpRequests(authorize -> authorize
                .requestMatchers(HttpMethod.POST, "/usuario").permitAll()
                .anyRequest().authenticated()
            )
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

        return http.build();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
        return configuration.getAuthenticationManager();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

eu estava usando o vscode usei o inteliji e ele marcou a classe do spring security em vermelho mais não fica nada marcado com vermelho

A principio não vi problemas no código. Como você está disparando a requisição?

http://localhost:8080/usuario estou usando assim no insominia, apenas o post esta dando 403

solução!

consegui resolver, o problema era que eu estava errando a senha do usuario :(