Validating JWT With Spring Boot and Spring Security
For my current project I will have a REST API set up with Spring Boot. To be able to use the API endpoint the application will check that the incoming request has a valid JWT token.
Join the DZone community and get the full member experience.
Join For FreeFor my current project I will have a REST API set up with Spring Boot (most likely running with BoxFuse). To be able to use the API endpoint the application will check that the incoming request has a valid JWT token provided earlier (by an API service that I trust).
To implement this functionality I want to make use of Spring Security as it fits nicely with Spring Boot. When Googling for information about this combination I ran into this site that describes the background information quite nicely, but didn’t give me all the necessary sources to get it running. So after some more investigating and trial & error, I finally came to a working solution. Note that in my situation I only needed to validate an incoming token, I don’t need to create or supply new tokens.
The source code of the example can be found here on GitLab. The example application has a REST Controller called MainController. After starting the application (by running the Application.main method) you can access the REST endpoint with: http://localhost:8888/hello?name=PalmApps. As you will see you will get an HTTP 401 error if you try this in your browser:
To get access to the endpoint you will need to supply a JWT token so you can get through the JwtAuthenticationFilter. To generate a valid token open the sources of the class JwtTokenGenerator and run the ‘main’ method, which will print a token in the console:
Copy the token and open a tool with which you can send an HTTP request and add the token to the header like Postman:
With the token in place you will see the expected output:
{
"id": 2,
"content": "Hello, PalmApps!"
}
If you access the endpoint http://localhost:8888/me with a POST request (still with the ‘Authorization’ header in place) you will get the details of the Principal object in JSON format:
{
"details": null,
"authorities": [
{
"authority": "admin"
}
],
"authenticated": true,
"principal": {
"username": "Pascal",
"token": "eyJhbGciOiJIUzUxMeJ9.eyJzdwIiOi....m72LpFADA",
"authorities": [
{
"authority": "admin"
}
],
"password": null
},
"credentials": null,
"name": "Pascal"
}
The ‘principal’ field in the returned object here is our AuthenticatedUser. If we get want to get more information from our JWT then we can simply add it to this object and fill it in the JwtAuthenticationProvider.
Published at DZone with permission of $$anonymous$$. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments