GumGum Tech Blog
Published in

GumGum Tech Blog

Let The Right One In…With Spring Security Annotations

Photo by Clément Falize on Unsplash

The Setup

Straight out of the box, SpringBoot has a lot of built-in security features that users can utilize to secure their applications. From authentication to role-based authorization, there’s a good base to secure any application. A lot of these features can be further extended to satisfy myriad use-cases, but this article will primarily focus on endpoint authorization, with an emphasis on keeping a user’s eyes on their own data. This will be done by constructing custom Spring Expression Language (SpEL) expressions for use with Spring’s method security annotations, so click on the preceding links if a refresher is needed.

Schema for our Example
CompanyData.kt, assume uniqueness for (companyId, data) pair
Photo by Dima Pechurin on Unsplash

Shutting The Door

So, as it stands, the service layer is wide open. To close it, validation must occur that the current user has access to the company. Assuming that the email can be obtained from retrieving the current user’s details, Spring can retrieve their respective User object and ensure that their list of companies includes the company being queried. In this case, it is assumed there is a SecurityUtils class that allows retrieval of the current user from the SecurityContext, casts to a concrete UserDetails class, and retrieves the user’s email. So, knowing that access to the current user’s email is available, something like the following can be done: with authorization
Photo by Sheldon Kennedy on Unsplash

Expanding on this

The vampires are outside the door now, but what happens when they try the window? The best part of how this @PreAuthorize annotation was constructed is that it is extremely reusable. Any method in the service layers that take in a companyId parameter can have this annotation applied! The CompanyUserAuthorization class could also be expanded to include methods that handle request objects, lists of company ids, etc. All that would need to be done is to construct their respective SpEL strings.

Photo by David Menidrey on Unsplash

Wrapping Up

Securing an application’s endpoints can be accomplished in a number of ways, but as shown in this article, @PreAuthorize can be used in conjunction with re-usable custom methods and SpEL expressions to secure method calls at the service level. Similar methods can be constructed using a variety of parameter types or even alongside @PostAuthorize if the object being compared for authorization resides in the return object.



We’re hiring! Check out

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store