4

Using Spring Security 3.1.3.RELEASE

So if there are a list of roles (over 10) and there is a need to block just ONE from accessing a Spring Controller method. Can this be done using Spring Expression Language, and avoid listing each and very accepted role?

For example, by including the Not sign.

@PreAuthorize("!hasRole('ROLE_FREE_USER')")

over listing all the roles like this

@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_PAID_USER','ROLE_PREM_USER',...)

I've looked at the documentation over here: http://static.springsource.org/spring-security/site/docs/3.0.x/reference/el-access.html

But there seems to be nothing on the NOT EQUAL to cases. Anyone face similar issue?

MasterV
  • 1,162
  • 1
  • 13
  • 18

2 Answers2

3

I'm pretty sure that NOT-sign (!) is supported in Spring Expression Language (SPEL). Naturally, it returns a boolean result.

An Example from the official documentation:

// evaluates to false
boolean falseValue = parser.parseExpression("!true").getValue(Boolean.class);

// -- AND and NOT --
String expression =  "isMember('Nikola Tesla') and !isMember('Mihajlo Pupin')";
boolean falseValue = parser.parseExpression(expression).getValue(societyContext, Boolean.class);
Matt
  • 9,068
  • 12
  • 64
  • 84
Boris Treukhov
  • 17,493
  • 9
  • 70
  • 91
  • 1
    Thanks for the doc. You are right about SPEL and not sign. Here is more recent documentation: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/expressions.html#expressions-language-ref – MasterV Jan 11 '13 at 00:04
0

Spring Expression Language didn't work for me in this case. Initially I tried with the following,

@RequestMapping("/post/edit")
        @PreAuthorize("hasRole('ROLE_OWNER') AND !hasRole('ROLE_ADMIN')")
        public String editPost(Model model, Principal principal,  HttpServletRequest request, @RequestParam("postId") String postId) {
    }

However, I had to recheck the Role from inside the method and redirect the page in case user has Admin Privileges.

@RequestMapping("/post/edit")
    @PreAuthorize("hasRole('ROLE_OWNER')")
    public String editPost(Model model, Principal principal,  HttpServletRequest request{

        //Admin Users does not have access to post edit page
        if (request.isUserInRole("ROLE_ADMIN")) {
            return TemplateNamesConstants.POST_WALL;
        }
}

Do update this thread in case you found a better/alternate solution.

Cnf271
  • 302
  • 5
  • 16