2012-02-08 3 views
2

У меня есть какой-то контроллер:Secure RESTful веб-метод в Spring MVC

@Controller 
    public class DefaultController { 

    @RequestMapping(value="/index.html", method=RequestMethod.GET) 
     public String indexView(){ 
      return "index"; 
     } 

    @RequestMapping(value="/some.action", method=RequestMethod.POST) 
    @ResponseBody 
     public MyObject indexView(some parametrs....){ 
      MyObject o= daoService.getO(id); 
        return o; 
     } 
} 

Я использую Spring Security:

<security:global-method-security secured-annotations="enabled" /> 
<security:http auto-config="true" access-denied-page="/accessDenied.jsp"> 
    <security:form-login login-page="/login.html" login-processing-url="/login" authentication-failure-url="/login.html?login_error=1" default-target-url="/"/> 
    <security:http-basic/> 
    <security:intercept-url pattern='/**' access='ROLE_USER' /> 
    <security:logout logout-url="/logout" logout-success-url="/"/> 
    <security:remember-me services-ref="rememberMeServices"/> 
    </security:http> 

Теперь моя проблема заключается в следующем го:

при доступе /some.action с использованием AJAX без аутентифицированного пользователя Spring Security возвращает команду 301 (перенаправление на страницу отказа от доступа).

Что мне нужно, даже если пользователь не прошел аутентификацию, чтобы вернуть 200 OK и отправить сообщение об ошибке проверки подлинности клиенту или событию или в худшем случае, чтобы вернуть ошибку 400.

Я понимаю, что мне нужно создать собственный обработчик успеха проверки подлинности, но могу ли я это сделать и как я могу применить этот обработчик к URI * .action?

+0

btw wouldnt 401 будет правильным кодом для возврата? http://stackoverflow.com/questions/3297048/403-forbidden-vs-401-unauthorized-http-responses – flurdy

+0

@flurdy, да 401 имеет смысл. –

+0

это может помочь http://www.byteclip.com/spring-security-post-authentication-logic/, таким образом вы можете изменить код ответа HTTP –

ответ

2

Для проверки подлинности AJAX я добавил пользовательскую точку доступа безопасности, чтобы проверить, проверен ли пользователь. Если это не так, я отправляю им код ошибки 4xx. Затем по моему вызову Ajax я проверяю, возвращается ли ошибка, и если да, я перенаправляю их на мою страницу входа.

Вот фрагмент моей конфигурации безопасности.

<security:http entry-point-ref="myAuthenticationEntryPoint" auto-config="true" use-expressions="true"> 
... 
... 
</security:http> 
<bean id="myAuthenticationEntryPoint" class="com.security.AjaxAuthenticationEntryPoint" > 
     <property name="loginFormUrl" value="/login"/> 
</bean> 

Вот мой заказ точка входа:

public class AjaxAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint 
{ 
    @Override 
    /** 
    * This method only gets call when the user logs out or when the session is invalid 
    * 
    * It checks to see if the request is an ajax request 
    * if so then return an error 
    * else then do the natural check 
    */ 
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) 
      throws IOException, ServletException 
    {      
     if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) 
     { 
      if (request.getSession() != null) 
      { 
       Object targetUrl = request.getSession().getAttribute(WebAttributes.SAVED_REQUEST); 
       if (targetUrl != null) 
       {     
        response.sendError(HttpServletResponse.SC_EXPECTATION_FAILED);          
       } 
      } 
     } 
     else 
     { 
      super.commence(request, response, authException); 
     } 

    } 
} 

Вот отрывок из моего звонка JQuery, перезарядка приводит к странице входа, чтобы появиться.

error: function (xhr, textStatus, errorThrown) 
       {  
        // 417 is sent from the server to indicate that 
        // page needs to be reloaded 
        // 
        if (xhr.status == 417) 
        { 
         xhr = null; 
         window.location.reload();      
        } 
       } 
Смежные вопросы