Mihkel Müür
Mihkel Müür

Reputation: 2192

How to show JSP content based on user's access to URLs with Spring Security

If you want to show content in JSP page based on user's access to one or more URLs, it is easy to do based on user's access to one URL:

<sec:authorize url="/someurl">
    <!-- show content, if someurl is accessible -->
</sec:authorize>

However, sometimes it may come to be handy to show content based on some boolean expression on user's accessible URL, something like (incorrect):

<sec:authorize url="!'/someurl'">
    <!-- show content, if someurl is inaccessible -->
</sec:authorize>

or

<sec:authorize url="'/someurl1' and '/someurl2'">
    <!-- show content, if someurl1 and someurl2 are accessible -->
</sec:authorize>

So far I have come up with a dirty solution using Spring EL construct with a static method in a custom class:

<sec:authorize access="!T(my.package.MyClass).isAccessibleToUser('/someurl')">
    <!-- show content, if someurl is inaccessible -->
</sec:authorize>

Is there some more elegant way to achieve this?

Upvotes: 2

Views: 1254

Answers (1)

Jan Vladimir Mostert
Jan Vladimir Mostert

Reputation: 12972

I would just put that logic in the controller being associated with the page instead of cramming it all in on the frontend, or if you're using Spring MVC, the better solution would be to create a RequestInterceptor class .

public class RequestInterceptor extends HandlerInterceptorAdapter {
    @Override
        public void postHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler,
            ModelAndView modelAndView) throws Exception {

            // logic here that checks if the user can see something
            modelAndView.addObject("canUserSeeSection", abooleanvalue);

            super.postHandle(request, response, handler, modelAndView);
        }
    }
}

and then in your frontend you can get away with standard JSP if tags using

<c:if test="${canUserSeeSection}" ... 

The same idea should also work for SpringSecurity tags.

Upvotes: 1

Related Questions