DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Frequently Used Annotations in Spring Boot Applications
  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS
  • Java, Spring Boot, and MongoDB: Performance Analysis and Improvements
  • Component Tests for Spring Cloud Microservices

Trending

  • The Convergence of Testing and Observability
  • Microservices With Apache Camel and Quarkus (Part 5)
  • Mastering Persistence: Why the Persistence Layer Is Crucial for Modern Java Applications
  • What Is Kubernetes RBAC and Why Do You Need It?
  1. DZone
  2. Coding
  3. Frameworks
  4. Writing Your Spring Security Expression Language Annotation

Writing Your Spring Security Expression Language Annotation

Spring security expression language is very useful. It helps secure your service/web methods with one line of code.

Boris Lam user avatar by
Boris Lam
·
Aug. 21, 12 · Tutorial
Like (3)
Save
Tweet
Share
42.48K Views

Join the DZone community and get the full member experience.

Join For Free

Spring security expression language is very useful. It helps secure your service/web methods with one line of code. It supports @PreAuthorize and @Secured. In the next three posts, I will talk about how to add custom behaviour to the @PreAuthorize annotation. 

Part 1 - Customize "hasPermission()" expression 
Part 2 - Add new customize method security expression 
Part 3 - Override default behaviour of spring security expression (e.g. hasRole() , permitAll() ...)

In this post, I will discuss how to add custom rules for permission-checking in your application. This is somewhat similar to what is described in Sold Craft's post. You can reference it for more details.

Step 1: Add configuration in your spring security xml file.

You should first add the DefaultMethodSecurityExpressionHandler. It will instantiate a default MethodSecurityExpressionRoot which provides you all the default security expression (e.g. isAuthenticated(), isAnonymous(),etc.). 

Besides, you have to add a permissionEvaluator for that ExpressionHandler. If you are using spring security ACL, you could use AclPermissionEvaluator. In our case, we would create a BasePermissionEvaluator as our permission evaluator. You will see in step 2 that we would define custom rules in this permission evaluator.

<sec:global-method-security pre-post-annotations="enabled">

  <sec:expression-handler ref="expressionHandler"/>
</sec:global-method-security>

<bean id="expressionHandler" class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandlerr">
    <property name="permissionEvaluator" ref="permissionEvaluator"/>
</bean>  

<bean id="permissionEvaluator" class="org.borislam.security.BasePermissionEvaluator"/>

Step 2: Create your PermissionEvaluator class

You must define a class that implements the org.springframework.security.access.PermissionEvaluator. You have to override the hasPermission() method and define custom rules in this class.

In my example, the user object contains a HashMap which stores the permissions of the user. I will check the permission String against this Hashmap. This HashMap is populated during login by a filter. This part will not be skipped in this example. 

For simplicity I just ignore the targetDomainObject parameter in my example. By using the targetDomainObject, you can further define security rules on certain domain objects in your application.

public class BasePermissionEvaluator implements PermissionEvaluator{

 @Override
 public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
  boolean hasPermission = false;
  if ( authentication != null &&  permission instanceof String){

   //implement the permission checking of your application here   
   //you can just check if the input permission is within your permission list

   //In my example, the user object contains a HashMap which stored the permission of the user.
   //The HashMap<String, PrivilegeResult> is populated during using login by filter. This will not be shown in this example 

   User user = SecurityUtil.getUserCredential();
   HashMap<String, PrivilegeResult> pMap =user.getPrivilegeMap();
   PrivilegeResult privResult = pMap.get(permission); 
   hasPermission =  privResult.isAllowAccess();

  } else {
   hasPermission =false; 
  }
  return hasPermission;
 }

 @Override
 public boolean hasPermission(Authentication authentication,
   Serializable targetId, String targetType, Object permission) {
    throw new RimtimeException("Id and Class permissions are not supperted by this application");
 }
}

Step 3: Example usage

You could simply add your @PreAuthorize("hasPermission()") to secure your method.

@PreAuthorize("hasPermission(#user, 'allowDoSomething')")
 public String doSomething()
 {
  //do something
  System.out.println("Do something");
 } 

Original Post

 

Spring Security Spring Framework Annotation

Opinions expressed by DZone contributors are their own.

Related

  • Frequently Used Annotations in Spring Boot Applications
  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS
  • Java, Spring Boot, and MongoDB: Performance Analysis and Improvements
  • Component Tests for Spring Cloud Microservices

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: