spring - 如何在 Spring MVC-Spring Security 应用程序中处理 GWT RPC 调用的 session 过期异常

标签 spring spring-mvc spring-security gwt-rpc

我有 Spring MVC 应用程序,其中安全性由 Spring Security 处理。

UI 是使用 GWT 构建的,它使用 RPC 方法从服务器获取数据。

我需要在 UI 上处理 session 过期的情况: 例如,RPC AsyncCallback 可以获取 SessionExpiredException 类型的异常,并弹出窗口,显示“您的 session 已过期,请单击刷新链接”之类的消息。

有人解决过这样的问题吗?

谢谢。

最佳答案

我想,为了处理传入的 GWT 调用,您可以使用一些 Spring MVC Controller 或一些 servlet。它可以有以下逻辑

try{
    // decode payload from  GWT call
    com.google.gwt.user.server.rpc.RPC.decodeRequest(...)
    // get spring bean responsible for actual business logic
    Object bean = applicationContext.getBean(beanName);
    // execute business logic and encode response
    return RPC.invokeAndEncodeResponse(bean, ….)
} catch (com.google.gwt.user.server.rpc.UnexpectedException ex) {
    // send unexpected exception to client
    return RPC.encodeResponseForFailure(..., new MyCustomUnexpectedException(), …) ;
}

本例的解决方案

HttpServletRequest request = getRequest() ; 
if (request.getRequestedSessionId() != null && !request.isRequestedSessionIdValid()) {
    return RPC.encodeResponseForFailure(..., new MyCustomSessionExpiredException(), …) ;
} else {
    // first code snippet goes here
}

然后在客户端代码中捕获自定义 session 过期异常。如果您不直接使用 RPC,请提供有关 GWT 和 Spring 之间的桥接实现的更多详细信息。

您还需要强制 GWT 编译器将 MyCustomSessionExpiredException 类型包含到序列化白名单中(以防止 GWT 安全策略停止向客户端传播异常的情况)。解决方案:将 MyCustomSessionExpiredException 类型包含到每个同步接口(interface)的每个方法签名中:

@RemoteServiceRelativePath("productRpcService.rpc")
public interface ProductRpcService extends RemoteService {
    List<Product> getAllProducts() throws ApplicationException;
    void removeProduct(Product product) throws ApplicationException;
}

MyCustomSessionExpiredException extends ApplicationException

然后在客户端代码中显示弹出窗口:

public class ApplicationUncaughtExceptionHandler implements GWT.UncaughtExceptionHandler {
    @Override        
    public void onUncaughtException(Throwable caught) {
        if (caught instanceof MyCustomSessionExpiredException) {
            Window.alert("Session expired");
        }
    }
}

// Inside of EntryPoint.onModuleLoad method
GWT.setUncaughtExceptionHandler(new ApplicationUncaughtExceptionHandler());

关于spring - 如何在 Spring MVC-Spring Security 应用程序中处理 GWT RPC 调用的 session 过期异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13821984/

相关文章:

java - SecurityContextHolder.getContext() 使用 @Async 时的 NPE

java - 我可以在 Hazelcast 中使用 LinkedHashMap 吗?

spring-mvc - 如何使用 Groovy 模板处理 bool 属性?

grails - 在Spring Security中进行身份验证后,Grails 3将我重定向到auth.html

Spring MVC Spring 安全性和错误处理

Grails Spring 安全/Acegi。自定义用户+密码过期管理

java - 无法从 activeMQ 中的内容构建正文 - 使用 Spring 通用消息

java - Spring MVC中如何使用anchor标签在当前jsp中找到固定位置?

java - Springboot Whitelabel 错误页面,状态为 404 : unable to resolve path of JSP

java - 在 Spring 3.2 中禁用路径变量中的空格修剪