JWT Token Scopes with Spring Security Roles

Sajith vijesekara
2 min readMay 5, 2020

These days I am working on project which need to validate jwt token & based on scopes we have to enable API end point to different users.

What is JWT ?

Json web Token Is Standard secure transmitting data between parties.JWT can be sign secure or public / private key pair.

In jwt there are three parts available header, payload, signature . This tutorial we are going cover how to handle scope based security in spring security.

Requirement

There are two end point /admin and /user . So In JWT Token scope values we have to allow admin end point for “admin” scope & user end point for “user” scope.

Solution

As First Step Add the Spring security Configs. [security configs & Filters]

Second step add the Authentication Entry point.

And most important part is add Add the filter for Handle Each Request Authentication.

And This is the Util Class written for Handle All Token Related functions.

Note : getGrantedValues method convert JWT token scopes to Security roles. Make sure you have to Add “ROLE_” to As prefix for ROLE.

And Last using PreAuthorize annotation each end point we can set what is the security role it will allowed.

Thanks & Happy Coding.

--

--

Sajith vijesekara

Technical Lead. Passionate about cloud computing & web security | Freelance Mobile Developer| CKAD | AWS Community Builder 🇱🇰