-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApiKeyAuthenticationFilter.java
More file actions
66 lines (55 loc) · 2.57 KB
/
Copy pathApiKeyAuthenticationFilter.java
File metadata and controls
66 lines (55 loc) · 2.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.healthbridge.integration.config;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.util.List;
@Component
public class ApiKeyAuthenticationFilter extends OncePerRequestFilter {
private static final String HEADER_NAME = "X-API-Key";
private final AppAuthProperties authProperties;
private final List<RequestMatcher> excludedMatchers = List.of(
new AntPathRequestMatcher("/actuator/**"),
new AntPathRequestMatcher("/v3/api-docs/**"),
new AntPathRequestMatcher("/swagger-ui/**"),
new AntPathRequestMatcher("/swagger-ui.html")
);
public ApiKeyAuthenticationFilter(AppAuthProperties authProperties) {
this.authProperties = authProperties;
}
@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
return excludedMatchers.stream().anyMatch(matcher -> matcher.matches(request));
}
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
String expectedApiKey = authProperties.apiKey();
if (expectedApiKey == null || expectedApiKey.isBlank()) {
filterChain.doFilter(request, response);
return;
}
String presentedKey = request.getHeader(HEADER_NAME);
if (!expectedApiKey.equals(presentedKey)) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().write("Missing or invalid API key");
return;
}
var authentication = new UsernamePasswordAuthenticationToken(
"api-client",
null,
List.of(new SimpleGrantedAuthority("ROLE_SYSTEM"))
);
SecurityContextHolder.getContext().setAuthentication(authentication);
filterChain.doFilter(request, response);
}
}