DEV Community

Davi
Davi

Posted on • Edited on

Forum Import rev MySQL

Passo 1: Configuração do Projeto
Crie um novo projeto Spring Boot e adicione as seguintes dependências no arquivo pom.xml (se estiver usando o Maven):

<dependencies> <!-- Spring Boot Starter Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Spring Boot Starter Data JPA --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- Spring Boot Starter Security --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- MySQL Connector --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies> 
Enter fullscreen mode Exit fullscreen mode

Passo 2: Configuração do Banco de Dados
Configure as propriedades de conexão com o banco de dados MySQL no arquivo application.properties:

spring.datasource.url=jdbc:mysql://localhost:3306/db_name spring.datasource.username=db_username spring.datasource.password=db_password 
Enter fullscreen mode Exit fullscreen mode

Substitua db_name, db_username e db_password pelos valores apropriados do seu ambiente.

Passo 3: Criar a Entidade do Usuário
Crie uma entidade JPA que representará o usuário no banco de dados:

@Entity public class Usuario { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String login; private String senha; private String token; // Construtores, getters e setters } 
Enter fullscreen mode Exit fullscreen mode

Passo 4: Criar o Repositório do Usuário
Crie um repositório JPA para realizar operações no banco de dados relacionadas ao usuário:

@Repository public interface UsuarioRepository extends JpaRepository<Usuario, Long> { Usuario findByLogin(String login); } 
Enter fullscreen mode Exit fullscreen mode

Passo 5: Criar o Serviço de Autenticação
Crie um serviço que será responsável por lidar com a autenticação e geração de tokens:

@Service public class AuthenticationService { @Autowired private UsuarioRepository usuarioRepository; public String generateToken(String login) { // Implemente aqui a lógica para gerar o token (pode ser aleatório ou baseado no login, por exemplo) return UUID.randomUUID().toString(); } public boolean authenticate(String login, String senha) { Usuario usuario = usuarioRepository.findByLogin(login); if (usuario != null && usuario.getSenha().equals(senha)) { String token = generateToken(login); usuario.setToken(token); usuarioRepository.save(usuario); return true; } return false; } public boolean checkToken(String token) { Usuario usuario = usuarioRepository.findByToken(token); return usuario != null; } } 
Enter fullscreen mode Exit fullscreen mode

Passo 6: Configurar o Spring Security
Crie uma classe de configuração do Spring Security para definir as regras de autenticação e autorização:

@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private AuthenticationService authenticationService; @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("/login").permitAll() .anyRequest().authenticated() .and() .formLogin().loginPage("/login"); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(new CustomAuthenticationProvider(authenticationService)); } } 
Enter fullscreen mode Exit fullscreen mode

Passo 7: Implementar o CustomAuthenticationProvider
Crie um provedor de autenticação personalizado para verificar as credenciais do usuário e definir a autenticação:

public class CustomAuthenticationProvider implements AuthenticationProvider { private final AuthenticationService authenticationService; public CustomAuthenticationProvider(AuthenticationService authenticationService) { this.authenticationService = authenticationService; } @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String login = authentication.getName(); String senha = authentication.getCredentials().toString(); if (authenticationService.authenticate(login, senha)) { return new UsernamePasswordAuthenticationToken(login, senha, new ArrayList<>()); } throw new BadCredentialsException("Credenciais inválidas."); } @Override public boolean supports(Class<?> authentication) { return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication); } } 
Enter fullscreen mode Exit fullscreen mode

Passo 8: Implementar as Páginas de Login e Acesso Restrito
Crie páginas para a autenticação do usuário e páginas de acesso restrito. Por exemplo, crie um controlador para exibir a página de login e a página após o login com token:

@Controller public class AuthController { @GetMapping("/login") public String loginPage() { return "login"; } @GetMapping("/home") public String homePage() { return "home"; } } 
Enter fullscreen mode Exit fullscreen mode

Lembre-se de criar as respectivas páginas HTML para "login" e "home".

Passo 9: Implementar as Rotas Protegidas
Para proteger as páginas de acesso restrito, você pode configurar o Spring Security para exigir autenticação para determinadas rotas. Você pode fazer isso no método configure(HttpSecurity http) da classe SecurityConfig. Por exemplo:

@Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("/login").permitAll() .antMatchers("/home").authenticated() .anyRequest().authenticated() .and() .formLogin().loginPage("/login"); } 
Enter fullscreen mode Exit fullscreen mode

Dessa forma, somente os usuários autenticados (com token válido) poderão acessar a rota /home e outras rotas não configuradas explicitamente.

Passo 10: Implementar o Controller para o Login
Crie um controlador para processar a requisição de login e realizar a autenticação:

@Controller public class AuthController { @Autowired private AuthenticationService authenticationService; @PostMapping("/login") public String login(@RequestParam String login, @RequestParam String senha) { if (authenticationService.authenticate(login, senha)) { return "redirect:/home"; } else { return "login"; } } } 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)