Skip to content

Commit

Permalink
Merge pull request HideyoshiSolutions#43 from HideyoshiSolutions/devel
Browse files Browse the repository at this point in the history
Devel - Fixes Auth Filter for Health Checker
  • Loading branch information
HideyoshiNakazone committed Feb 16, 2024
2 parents 078373c + 19bd986 commit 66e87f0
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 22 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ private void addSecurityToHttp(HttpSecurity http) throws Exception {

http.authorizeRequests()
.antMatchers("/session/**").permitAll()
.and().authorizeRequests().antMatchers("/health").permitAll()
.and().authorizeRequests().antMatchers("/user/signup").permitAll()
.and().authorizeRequests().antMatchers("/user/oauth/**").permitAll()
.and().authorizeRequests().antMatchers("/user/login/**").permitAll()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hideyoshi.backendportfolio.base.security.service.AuthService;
import com.hideyoshi.backendportfolio.util.exception.AuthenticationInvalidException;
import com.hideyoshi.backendportfolio.util.exception.AuthenticationInvalidExceptionDetails;
import com.hideyoshi.backendportfolio.util.exception.BadRequestException;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
Expand All @@ -11,6 +15,7 @@
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

import static org.springframework.http.HttpHeaders.AUTHORIZATION;
Expand All @@ -20,9 +25,12 @@
public class CustomAuthorizationFilter extends OncePerRequestFilter {

private static final List<String> notProtectedPaths = Arrays.asList(
"/health",
"/user/login",
"/user/signup",
"/user/login/refresh"
"/user/login/refresh",
"/session/validate",
"/session/destroy"
);

private static final String AUTHORIZATION_TYPE_STRING = "Bearer ";
Expand All @@ -38,37 +46,41 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
throws ServletException, IOException {
if (this.isPathNotProtected(request.getServletPath())) {
filterChain.doFilter(request, response);
} else {
String authorizationHeader = request.getHeader(AUTHORIZATION);
if (Objects.nonNull(authorizationHeader) && authorizationHeader.startsWith(AUTHORIZATION_TYPE_STRING)) {
try {
return;
}

UsernamePasswordAuthenticationToken authenticationToken =
this.authService.verifyAccessToken(authorizationHeader);
String authorizationHeader = request.getHeader(AUTHORIZATION);

SecurityContextHolder.getContext().setAuthentication(authenticationToken);
filterChain.doFilter(request, response);
try {
UsernamePasswordAuthenticationToken authenticationToken =
this.validateUserAccess(authorizationHeader);

} catch (Exception e) {
response.setHeader("error", e.getMessage());
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
filterChain.doFilter(request, response);

response.setStatus(FORBIDDEN.value());
} catch (Exception e) {
response.setHeader("error", e.getMessage());
response.setStatus(FORBIDDEN.value());

Map<String, String> error = new HashMap<>();
error.put("error_message", e.getMessage());
AuthenticationInvalidExceptionDetails error = new AuthenticationInvalidExceptionDetails("Authentication Failed. Check your credentials.",
HttpStatus.FORBIDDEN.value(), e.getMessage(),
e.getClass().getName(), LocalDateTime.now());

response.setContentType(APPLICATION_JSON_VALUE);
new ObjectMapper()
.writeValue(response.getOutputStream(), error);
}
} else {
filterChain.doFilter(request, response);
}
response.setContentType(APPLICATION_JSON_VALUE);
new ObjectMapper()
.writeValue(response.getOutputStream(), error);
}
}

private Boolean isPathNotProtected(String path) {
return notProtectedPaths.contains(path);
}

private UsernamePasswordAuthenticationToken validateUserAccess(String authorizationHeader) {
if (Objects.nonNull(authorizationHeader) && authorizationHeader.startsWith(AUTHORIZATION_TYPE_STRING)) {
return this.authService.verifyAccessToken(authorizationHeader);
} else {
throw new AuthenticationInvalidException("Access denied");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hideyoshi.backendportfolio.base.user.service.UserService;
import com.hideyoshi.backendportfolio.util.exception.AuthenticationInvalidException;
import com.hideyoshi.backendportfolio.util.exception.BadRequestException;
import com.hideyoshi.backendportfolio.util.guard.UserResourceGuard;
import lombok.RequiredArgsConstructor;
Expand Down Expand Up @@ -36,7 +37,7 @@ public boolean preHandle(final HttpServletRequest request, final HttpServletResp
Boolean accessPermission =
annotation.accessType().hasAccess(this.userService, this.objectMapper, request);
if (!accessPermission) {
throw new BadRequestException(annotation.denialMessage());
throw new AuthenticationInvalidException(annotation.denialMessage());
}
}
return true;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package com.hideyoshi.backendportfolio.healthChecker.api;


import com.hideyoshi.backendportfolio.util.guard.UserResourceGuard;
import com.hideyoshi.backendportfolio.util.guard.UserResourceGuardEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
Expand All @@ -11,9 +14,11 @@
@Log4j2
@Controller
@RestController
@RequiredArgsConstructor
@RequestMapping("/health")
public class HealthCheckerController {
@RequestMapping
@UserResourceGuard(accessType = UserResourceGuardEnum.OPEN)
public ResponseEntity<String> healthCheck() {
log.info("Health check requested");
return ResponseEntity.ok("Health check successful!");
Expand Down

0 comments on commit 66e87f0

Please sign in to comment.