0

I have a method annotated with @PreAuthorize(...) with some logic that goes away and queries an API for some information about what the user can view. However, I have this endpoint that I need to add this @PreAuthorize annotation into which receives in a more "complex" object which I want to transform slightly (the object contains an array that is some cases I want to add/remove data from).

@PostMapping("/search")
@PreAuthorize("@Service.isAuth(#searchParam)")
public ResponseEntity<Response> search(SearchParams searchParam) {
    return service.getSearchResult(searchParam);
}

Is there a way I can modify searchParam inside the @PreAuthorize annotation then have it passed into the method body, I know that this is probably is not the correct way to do this and maybe isn't something that @PreAuthorize wasn't designed for but is there any way of doing this even with a different type of annotation. Obviously worst case I can move the logic into the method body but I would prefer to use an annotation-based solution like @PreAuthorize offers if possible. Thanks for any help even links to other relevant things would be useful I've not found much on google related to this.

1 Answer 1

1

I think the best solution is to make a handler/interceptor and then annotate it with @PreAuthorize. So I think you are in the right track but you need to make sure that you modify your code to implement the HandlerMapping interface to create the interceptor and then override the prehandle method. After you need to annotate it with @PreAuthorize programatically. The last thing will be to use a wrapper to modify the HttpWrapper, it cannot be done manually. Here links to the relevant resources in order:

Have a try, hopefully that works.

Snippet of code taken from second link uses a programatic PreAuthorize rather than annotation:

public class PreAuthorizeChecker implements HandlerInterceptor {

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    if (handler instanceof HandlerMethod) {
        HandlerMethod hm = (HandlerMethod) handler;
        PreAuthorize annotation = AnnotationUtils.findAnnotation(hm.getMethod(), PreAuthorize.class);
//TODO use the technique shown on the third link to wrap and modify the HttpServletRequest
        if (annotation == null) {
            // prevent access to method wihout security restrictions
            throw new RuntimeException("Rights are not defined for this handler");
        }

    }
    return true;
}

.....

Not the answer you're looking for? Browse other questions tagged or ask your own question.