springspring-mvcspring-securityspring-elspelevaluationexception

How to access objects inside model in @PostAuthorize using SpEL


I created this method just to explain the scenario. I would like to evaluate the user domain object inside the model object.

I know I can evaluate return objects and method arguments. But I got the following error when I tried with model object,**is it not possible to use model objects in PostAuthorize / PreAuthorize? **

Error

[Request processing failed; nested exception is java.lang.IllegalArgumentException: Failed to evaluate expression '#model.user.userName != 'ramesh''] with root cause org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 7): Field or property 'user' cannot be found on object of type 'org.springframework.validation.support.BindingAwareModelMap'

code

@PostAuthorize("#model.user.userName != 'ramesh'")
@RequestMapping(value="/createusername", method = RequestMethod.GET)
public String getCreateUserNamePage(ModelMap model) {
    User user = new User();
    String username = SecurityContextHolder.getContext().getAuthentication().getName();
    if(username!=null)
        user = customUserDetailsService.getUserByUsername(username);
    else
        user.setUserName(username);
    model.put("user", user);
    return "createusername";
}

Solution

  • Your model object doesn't have a property called "user", instead you're accessing it like this: model.put("user", user). It appears that your model (ModelMap) is some type of map.

    Does it extend java.util.Map?
    If so you can use the spel map syntax like this: #model[user].username