Update the AuthorizedInterceptor to return a JSON error instead of HTML.
continuous-integration/drone/push Build is passing
continuous-integration/drone/push Build is passing
This commit is contained in:
+31
-2
@@ -3,11 +3,17 @@ package space.kklochko.spring_rest_example.interceptors;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
import space.kklochko.spring_rest_example.security.access.AuthorizedValidator;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
public class AuthorizedInterceptor implements HandlerInterceptor {
|
||||
@Autowired
|
||||
AuthorizedValidator authorizedValidator;
|
||||
@@ -29,16 +35,39 @@ public class AuthorizedInterceptor implements HandlerInterceptor {
|
||||
}
|
||||
|
||||
if(accessStatus == null) {
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authorizedValidator.noToken());
|
||||
sendJsonError(response, HttpServletResponse.SC_UNAUTHORIZED, authorizedValidator.noToken());
|
||||
return false;
|
||||
}
|
||||
|
||||
if(!accessStatus) {
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authorizedValidator.accessDeniedNoPermission());
|
||||
sendJsonError(response, HttpServletResponse.SC_FORBIDDEN, authorizedValidator.accessDeniedNoPermission());
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private void sendJsonError(HttpServletResponse response, int status, String message) {
|
||||
response.setStatus(status);
|
||||
response.setContentType("application/json");
|
||||
|
||||
Map<String, Object> errorResponse = new TreeMap<>();
|
||||
errorResponse.put("error", message);
|
||||
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
String json;
|
||||
|
||||
try {
|
||||
json = objectMapper.writeValueAsString(errorResponse);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
try {
|
||||
response.getWriter().write(json);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user