I am using keyclock with springboot latest versions, I have been trying to authenticate users using api-key that is sent in header just like jwt
I found a way using filters in spring security, extract the api-key from the header and check the key before access endpoint, but this is not related with keyclock, the requirement is to use keyclock in this process, so how to generate api-key in keyclock and use this api-key in the header each time the client send, and in keyclock of filter check this api-key, the important point here is to make keyclock generate the api-key and play the central point in this process
this is my already defined code
ApiKeyAuthFilter.java
@Component
public class ApiKeyAuthFilter extends OncePerRequestFilter {
@Value("${api.key}")
private String key;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String apiKey = request.getHeader("X-API-KEY");
if (apiKey != null && apiKey.equals(key)) {
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(apiKey, null,
List.of(new SimpleGrantedAuthority("ROLE_SSS")));
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
filterChain.doFilter(request, response);
}
}
SecurityConfig.java
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
@Autowired
JwtAuthConverter jwtAuthConverter;
@Autowired
ApiKeyAuthFilter apiKeyAuthFilter;
@Bean
SecurityFilterChain resourceServerFilterChain(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated());
http.addFilterBefore(apiKeyAuthFilter, UsernamePasswordAuthenticationFilter.class);
http.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
return http.build();
}
}
but as you can see the key is defined in application.properties, this is not gonna help, I want the api-key is generated by the keyclock, and keyclock allow or decline the access of the endpoints
does keyclock support this process ?