@PreAuthorize and @PostAuthorize

The use of the @PreAuthorize and @PostAuthorize annotations is a preferred way to define the method-level annotations as it supports the use of Spring EL to be used to define the access control applied to the method. The @PreAuthorize annotation facilitates to authorize the user before entering the method while the @PostAuthorize annotation does the checking of the authorization after the execution of the method. The @PostAuthorize annotation is used on a limited situation, where the verification is done upon the values returned by the method. The following code snippet shows how to use the @PreAuthorize annotation to apply method-level security in the code:

@PreAuthorize("hasRole('ROLE_ADMIN')") 
   public String message() 
   { 
       //code goes here 
   } 

Now, we are well aware of the annotation facilitating developers to apply method-level security; however, by default, these are disabled. The method-level security is enabled by the following configuration in the XML file:

<security:global-method-security pre-post-annotations="enabled"      
  secured-annotations="enabled" jsr250-annotations="enabled" /> 

The attributes configured in the preceding configuration are as follows:

  • pre-post-annotations: The value of it determines whether to enable or disable the @PreAuthorize and @PostAuthorize annotations or not
  • secured-annotations: The value of the attribute specifies @Secured to be enabled or disabled
  • jsr250-annotations: The value of the attribute determines if JSR-250 annotations, such as @RolesAllowed, are enabled or not.
The configuration allows enabling more than one annotation; however, only one of them should be used for a method to properly define the security behavior.

In earlier discussions at a number of occasions, we discussed using Spring EL to enable the security in the annotations. The following table summarizes few of the mostly used expressions:

Expression to use

When to use

hasRole(name_of the_role)

This is used to specify the role that can access the method.

hasAnyRole(role1, role2)

This is used to specify multiple roles that can invoke the method.

permitAll

This will allow all the users to invoke the method.

denyAll

This will deny all the users to invoke the method.

isRememberMe()

This is used to determine whether the user is a remember-me user.

isAuthenticated()

This is used to determine whether the user is anonymous or not.

hasPermission(target_object, permission_object)

This expression evaluates that the target object has the specified permissions whether to invoke the method or not.

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

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