Accessing the http request in spring security custom expression

Viewed 940

I'm trying to write a custom spring security expression with PreAuthorize. I want to achieve this:

@PreAuthorize(customAuthCheck(param1, param2))
@RestController
public String getRestrictedInfo(HttpServletRequest request) {
    // 
}

where param1, param2 depends on the business logic.

In my AuthSecurityExpressionRoot class:

public class CustomMethodSecurityExpressionRoot extends SecurityExpressionRoot implements MethodSecurityExpressionOperations {
    public boolean customAuthCheck(String param1, String param2) {
        // check authorization
    }
}

The problem is, I want to access the http request (specifically, the "Authorization" header, and the httpMethod) inside the customAuthCheck method. How can I implement that?

1 Answers

You can pass the entire request to your MethodSecurityExpressionOperations object, then extract whatever headers you need. In your case, use this:

public class CustomMethodSecurityExpressionRoot extends SecurityExpressionRoot implements MethodSecurityExpressionOperations {
    public boolean customAuthCheck(HttpServletRequest request) {
        String jwtString = request.getHeader("Authorization");
        // decode/process the JWT
        // check authorization
    }
}

Then in your controller:

@PreAuthorize(customAuthCheck(#request))
@RestController
public String getRestrictedInfo(HttpServletRequest request) {
    // 
}

You can pass other params along with the header too, if you want, as long as they are part of the method signature, e.g.:

@PreAuthorize(customAuthCheck(#param1, #request))
public String getRestrictedInfo(HttpServletRequest request, @RequestParam String param1) {
    //
}
Related