【问题标题】:SPRING @RestController: Passing Cookie to a Service from Every MethodSPRING @RestController:将 Cookie 从每个方法传递给服务
【发布时间】:2017-06-21 17:06:12
【问题描述】:

我有一个@RestController,其中每个方法都需要将(WebSSO)cookie 传递给服务。该服务反过来使用 cookie 进行身份验证。我在控制器中自动装配服务 bean。该服务有一个设置器setCredentials(String webSSOCookie)。一种简单的方法是在每个方法中调用此设置器。我想做得更好;例如使用HandlerInterceptor。但是,HandlerInterceptor 无权访问控制器(因此也无法访问其成员) - 对吗?

jersey 中,我可以使用filter。我如何在 SPRING 中实现它?

@RestController
@RequestMapping("/documents")
public class ECMRestController {

    @Autowired
    public ECMService ecmService;   

    @RequestMapping(value="/{documentId}", method=RequestMethod.DELETE)
    public void deleteDocument(@RequestParam("documentId") String documentId) throws IllegalArgumentException, HttpClientErrorException {
         // I could get and pass the cookie to ecmService in every method.
         // ecmService.setCredentials(webSSOCookieObtainedfromRequest);
         // However I don't want to do it that way.
         ecmService.deleteDocument(documentId);
    }

   // Other REST Methods that need to pass the cookie in the same way.

}

【问题讨论】:

    标签: java spring spring-mvc cookies


    【解决方案1】:

    您可以请求 SecurityContextHolder 查询您在过滤器中自定义的当前身份验证。

    MyCustomAuth auth = (MyCustomAuth) SecurityContextHolder.getContext().getAuthentication();
    auth.getCookie();
    

    或者您可以在可以从任何地方检索的上下文中使用 ThreadLocal:

    public class CookieContext {
        private static final ThreadLocal<Cookie> COOKIE = new ThreadLocal<>();
        private static final CookieContext INSTANCE = new CookieContext();
    
        public void setCookie(Cookie value) {
            COOKIE.set(value);
        }
    
        public Cookie getCookie() {
            return COOKIE.get();
        }
    
        public static CookieContext getContext() {
            return INSTANCE;
        }
    }
    
    
    
    public class CookieInterceptor extends HandlerInterceptorAdapter {
    
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
            CookieContext context = CookieContext.getContext();
            context.setCookie(request.getCookies()[0]);
        }
    }
    

    【讨论】:

    • 我不需要安全原则。我需要将 cookie 传递给服务。我的 REST API 对调用者进行身份验证(通过 WebSSO 的方式)。生成的 cookie 需要传递给服务,该服务将“授权”调用者。实际上,它与安全性或 cookie 无关,它与在 Interceptor 中修改 Controller 的成员的能力有关。
    • 只需将其存储在您的身份验证对象中即可。但我猜你的设计有问题。你应该使用角色。
    • 您对设计存在问题的“猜测”是什么?有一个下游服务需要将 cookie 发送给它。 My Rest 需要获取 cookie(它可以很好地做到这一点)并使用每种方法发送它。我可以用每种方法发送 cookie,但这不是我想要的方式。应该有更好的方法;即在拦截器中或使用 AOP。只是我还不知道。我不相信你的帖子能回答这个问题。
    • 所以只需获取安全上下文,使用您自己的实现设置身份验证,该实现包含您可以从代码中的任何位置检索的 cookie。或者使用 ThreadLocal 创建您自己的上下文。是的,您可以使用 Aspect、Interceptor 或过滤器。
    猜你喜欢
    • 2010-11-08
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    相关资源
    最近更新 更多