@SecurityCheck

Now, let's implement a simplified security check to our Messages App. We will create an @SecurityCheck annotation, which can be applied to any method to perform a security check.

Here is what the @SecurityCheck annotation looks like:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SecurityCheck {
}

As you can see, this is a simple annotation that can be applied to methods.

And here is how the SecurityChecker aspect appears:

package app.messages;
...
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
...
@Aspect
@Component
public class SecurityChecker {
...
@Pointcut("@annotation(SecurityCheck)")
public void checkMethodSecurity() {}

@Around("checkMethodSecurity()")
public Object checkSecurity (ProceedingJoinPoint joinPoint) throws
Throwable {
logger.debug("Checking method security...");
// TODO Implement security check logics here
Object result = joinPoint.proceed();
return result;
}
}

As you can see, the SecurityChecker aspect is a regular Spring bean. What is special about it is that it has the @Aspect annotation. Spring supports XML-defined AOP configuration via the <aop:config> element, as well as the AspectJ annotations definition, which is the one we are using here.

Inside the SecurityChecker aspect, we create a pointcut signature, checkMethodSecurity()with the @Pointcut annotation by using the @annotation PCD for the @SecurityCheck annotation.

In the checkSecurity() advice, we use the @Around annotation to specify that the advice is around advice with the pointcut expression, "checkMethodSecurity()". Our advice is only implemented for demo purposes so that we only write a message to the log. In order to see the log message, you will need to add the following configuration to the application.properties file:

logging.level.app.messages.SecurityChecker=DEBUG

Now, the last step is to apply the @SecurityCheck annotation to the methods that we want to perform a security check. Let's apply it to the MessageService.save() method. Here is how the method appears:

@SecurityCheck
public Message save(String text) {
return repository.saveMessage(new Message(text));
}

If you restart the Messages App and call the /messages (POST) API, you will see a debug message similar to the following in the log:

...
app.messages.SecurityChecker : Checking method security...
app.messages.AuditingFilter : Request[uri=/messages, method=POST] completed in 273 ms

Spring Security uses Filter objects for request-level access control and AOP for method-level access control by using the @Secure annotation.

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

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