Spring AOP

Our Messages App is a simplified demo application. It doesn't have many features that a typical web application should have. For example, it lacks security checking. Currently, we allow anyone to post messages via the /messages (POSTAPI. A simple fix is to add  security check logic inside the API handler, the MessageController.saveMessage() method, as follows:

public ResponseEntity<Message> saveMessage(@RequestBody MessageData data) {
checkSecurity();
...
}

private void checkSecurity() throws NotAuthorizedException {
// Do security checking
...
}

Inside the saveMessage() method, we invoke the checkSecurity() method immediately and, if the request is not authorized, NotAuthorizedException will be thrown.

Our Messages App doesn't have a user system. Hence, we cannot check whether a request is from an authenticated user. However, there are still several types of security checking we can perform here. For example, we can only allow requests coming from a specific IP address. Requests from all other IP addresses will be considered not authorized. Or, we can hardcode credentials into the code and the client-side needs to pass them in the request header to pass the security checking. Owing to the scope of this book, we will implement security checking in our TaskAgile application.

This would work fine in our app. However, it would cause code duplication in applications that have dozens of APIs that need to execute security checking as you will see this boilerplate code at the beginning of every API handler.

It is preferable to perform security checking in a central place and, when the code execution reaches the API handler, the security has already been checked. From there, it does pose any further concern.

We can create SecurityFilterwhich will be responsible for security checking against requests. Inside the filter, we can use request.getRequestURI() and request.getMethod() to know which API the request is targeting and then check whether the request is authorized. This works perfectly when we only want security checking at the request-level.

In a complex application, you might want to check security at the method-level. For example, you might want to perform additional security checks on the MessageService.save() method. In such a case, performing security checking in Filter won't work. You will need to use AOP technology.

AOP is a different way of thinking about application structure compared with object-oriented programming. Let's introduce the basic concepts of AOP, before implementing security checking with AOP in our Messages App.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.22.164