简体   繁体   中英

Spring security - Secure a request by validating principle against @RequestParam parameter?

I work with Restful API (with many urls) using Spring 3.1.2, and want to apply security filters per request that uses both data from the authenticated user "principal" and the data sent by the request.

example:

validate accountId from request url:

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

with principal data principal.accountId = 23 .

I know this can be done from within the @requestMapping methods, but want to do it outside the actual method, so it will be maintainable and configurable without interfering the business logic.

But I didn't find any advice\\sample about it..

I believe it should look something like: @PreAuthorize("principal.accountId == requestParam.accountId")

I think you are looking for filters to filter the request and response. In Spring, you can use interceptors for this purpose.

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");
    }
}

Finally, you need to configure these interceptors in your context.xml file:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM