Я пытаюсь использовать Spring Security 3.0.5 в своем веб-приложении. В принципе, я хочу иметь веб-службу, которая возвращает данные в формате json через HTTP GET
.
Я реализовал службу RESTful, которая возвращает данные, когда запрашивается url http://localhost:8080/webapp/json
. Это отлично работает со следующей командой curl
> curl http://localhost:8080/webapp/json
{"key":"values"}
После добавления базовой аутентификации с использованием безопасности Spring я могу использовать следующие команды для получения данных
> curl http://localhost:8080/webapp/json
<html><head><title>Apache Tomcat/6.0.29 - Error report .....
> curl -u username:password http://localhost:8080/webapp/json
{"key":"values"}
Первая команда возвращает стандартную страницу ошибки tomcat, так как теперь она требует имени пользователя и пароля. Мой вопрос в том, можно ли обрабатывать доступ, запрещенный таким образом, что он выводит мое собственное сообщение об ошибке? i.e.
> curl http://localhost:8080/webapp/json
{"error":"401", "message":"Username and password required"}
Вот моя конфигурация безопасности Spring и AccessDeniedHandler
. Как вы можете видеть, я пытаюсь добавить access-denied-handler
, который просто выводит строку через ответ сервлета, но он по-прежнему не печатает мое собственное сообщение в командной строке.
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">
<global-method-security secured-annotations="enabled"/>
<beans:bean name="access-denied" class="webapp.error.JSONAccessDeniedHandler"></beans:bean>
<http auto-config="true">
<access-denied-handler ref="access-denied"/>
<intercept-url pattern="/json" access="ROLE_USER,ROLE_ADMIN" />
<http-basic />
</http>
<authentication-manager>
<authentication-provider>
<password-encoder hash="md5"/>
<user-service>
...
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
AccessDeniedHandler.java
package webapp.error;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
public class JSONAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
PrintWriter writer = response.getWriter();
writer.print("{\"error\":\"401\", \"message\":\"Username and password required\"}");
}
}