【问题标题】:Spring security - Secure a request by validating principle against @RequestParam parameter?Spring security - 通过验证 @RequestParam 参数的原则来保护请求?
【发布时间】:2014-06-18 14:41:37
【问题描述】:

我使用 Spring 3.1.2 使用 Restful API(带有许多 url),并希望为每个请求应用安全过滤器,该过滤器使用来自经过身份验证的用户“主体”的数据和请求发送的数据。

示例:

从请求 url 验证 accountId:

http://www.foo.com/accountRecords?accountId=23

主要数据principal.accountId = 23。

我知道这可以在@requestMapping 方法中完成,但希望在在实际方法之外完成,这样它就可以维护和配置,而不会干扰业务逻辑。

但我没有找到任何关于它的建议\示例..

我相信它应该看起来像: @PreAuthorize("principal.accountId == requestParam.accountId")

【问题讨论】:

    标签: java spring spring-mvc spring-security spring-el


    【解决方案1】:

    我认为您正在寻找过滤器来过滤请求和响应。在 Spring 中,您可以为此目的使用 interceptors。

    public class MyInterceptor extends HandlerInterceptorAdapter {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            HttpSession session = request.getSession(false);
            String requestParam = request.getParameter("your request param");
        }
    }
    

    最后,你需要在你的 context.xml 文件中配置这些拦截器:

    <mvc:interceptors>
            <mvc:interceptor>
                <mvc:mapping path="/**"/>
                <bean class="com.example.MyInterceptor" />
            </mvc:interceptor>                
        </mvc:interceptors>
    

    【讨论】:

    • 谢谢,我认为拦截器对我来说太高级了,在 Spring 文档中,拦截器是通过正则表达式和权限过滤的,但无法访问请求参数。如果您能提供示例代码,我将不胜感激。
    • 例如查看已编辑的答案。看你可以使用请求参数。
    • 我明白了。很好的例子 :) 你知道如何从 MyInterceptor 访问安全主体(例如用户名和帐户)吗?
    猜你喜欢
    • 2014-11-06
    • 2016-06-03
    • 2012-02-13
    • 2013-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多