编程语言
首页 > 编程语言> > 论坛导入rev MySQL

论坛导入rev MySQL

作者:互联网

确保您已使用Maven(或Gradle)设置了Java开发环境以进行依赖性管理。

以下是实施此系统的一步一步:

第1步:项目配置
创建一个新的Spring Boot项目,并将以下依赖项添加到pom.xml文件中(如果您使用的是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>

第2步:数据库配置
application.properties文件中配置连接到MySQL数据库的属性:

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

Substitua db_namedb_username e db_password pelos valores apropriados do seu ambiente.

第3步:创建用户实体
创建一个JPA实体,该实体将代表数据库中的用户:

@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
}

第4步:创建用户存储库
创建一个JPA存储库,对用户相关数据库执行操作:

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

第5步:创建身份验证服务
创建一个负责处理身份验证和令牌生成的服务:

@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;
    }
}

第6步:配置Spring Security
创建一个Spring Security配置类来定义身份验证和授权规则:

@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));
    }
}

第7步:实施CustomAuthenticationProvider
创建自定义身份验证提供程序来验证用户凭据并设置身份验证:

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);
    }
}

第8步:实现登录和限制访问页面
为用户身份验证和限制访问页面创建页面。例如,创建一个控制器来显示登录页面和令牌登录后的页面:

@Controller
public class AuthController {
    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }

    @GetMapping("/home")
    public String homePage() {
        return "home";
    }
}

记得为“登录”和“主页”创建各自的HTML页面。

第9步:实施受保护的路线
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");
}

通过这种方式,只有经过身份验证的用户(具有有效令牌)才能访问/home路由和其他未明确配置的路由。

第10步:实现登录控制器
创建一个控制器来处理登录请求并执行身份验证:

@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";
        }
    }
}

标签:rev MySQL,Java,Spring Boot
来源: