Bael 5711: Securing Spring Boot API with API key and secret (#14102)

* #bael-5711: add source

* #bael-5711: remove extra space

* #bael-5711: remove extra space

* #bael-5711: remove extra space

* #bael-5711: add custom message

* #bael-5711: refactor return null

---------

Co-authored-by: h_sharifi <h_sharifi@modernisc.com>
This commit is contained in:
Hamid Reza Sharifi 2023-05-25 13:17:53 +03:30 committed by GitHub
parent 75da1d17c6
commit f993296b0b
2 changed files with 20 additions and 5 deletions

View File

@ -1,5 +1,6 @@
package com.baeldung.apikeyauthentication.configuration;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;
@ -8,15 +9,28 @@ import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class AuthenticationFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
Authentication authentication = AuthenticationService.getAuthentication((HttpServletRequest) request);
SecurityContextHolder.getContext().setAuthentication(authentication);
try {
Authentication authentication = AuthenticationService.getAuthentication((HttpServletRequest) request);
SecurityContextHolder.getContext().setAuthentication(authentication);
} catch (Exception exp) {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
PrintWriter writer = httpResponse.getWriter();
writer.print(exp.getMessage());
writer.flush();
writer.close();
}
filterChain.doFilter(request, response);
}
}

View File

@ -1,5 +1,6 @@
package com.baeldung.apikeyauthentication.configuration;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import javax.servlet.http.HttpServletRequest;
@ -11,10 +12,10 @@ public class AuthenticationService {
public static Authentication getAuthentication(HttpServletRequest request) {
String apiKey = request.getHeader(AUTH_TOKEN_HEADER_NAME);
if (apiKey != null && apiKey.equals(AUTH_TOKEN)) {
return new ApiKeyAuthentication(apiKey, AuthorityUtils.NO_AUTHORITIES);
if (apiKey == null || !apiKey.equals(AUTH_TOKEN)) {
throw new BadCredentialsException("Invalid API Key");
}
return null;
return new ApiKeyAuthentication(apiKey, AuthorityUtils.NO_AUTHORITIES);
}
}