#1
Securing REST APIs ensures your data is protected while allowing only authorized users to access it. Let’s see how to secure a Firebird-backed API using Spring Boot.

1. Add Security Dependencies

Add the Spring Security dependency to your Maven project:
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
</dependency>
Spring Boot automatically adds basic authentication. You can customize it for your Firebird users.

2. Configure Firebird Authentication

Assume you have a users table in Firebird:
CREATE TABLE users (
  id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
  username VARCHAR(50),
  password VARCHAR(100),
  role VARCHAR(20)
);
Passwords should be encrypted before being stored (e.g., using BCrypt).

3. Create a User Entity and Repository

@Entity
public class User {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
    private String password;
    private String role;
}
public interface UserRepository extends JpaRepository<User, Long> {
    Optional<User> findByUsername(String username);
}

4. Implement UserDetailsService

Integrate Firebird users with Spring Security:
@Service
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired private UserRepository repo;

    @Override
    public UserDetails loadUserByUsername(String username) {
        User user = repo.findByUsername(username)
            .orElseThrow(() -> new UsernameNotFoundException("User not found"));
        return new org.springframework.security.core.userdetails.User(
            user.getUsername(), user.getPassword(),
            List.of(new SimpleGrantedAuthority("ROLE_" + user.getRole())));
    }
}

5. Define a Security Configuration

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
            .csrf().disable()
            .authorizeHttpRequests()
            .requestMatchers("/api/public/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .httpBasic()
            .and().build();
    }

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

6. Secure Your REST Endpoints

@RestController
@RequestMapping("/api")
public class SecureController {

    @GetMapping("/public/hello")
    public String publicHello() {
        return "Hello Public";
    }

    @GetMapping("/private/hello")
    public String privateHello() {
        return "Hello Secured";
    }
}
Now /api/private/hello requires authentication, while /api/public/hello is open.

7. Test the Security

Run the application.
Access /api/public/hello — no authentication needed.
Access /api/private/hello — browser will ask for credentials.
#ads

image quote pre code