Enable JWT Token Validation - OpenLegacy API
As an OpenLegacy API is a Springboot application, JWT validation can be enabled in just a few steps.
Because there are many ways to implement this, we decided to demonstrate this with Okta as a commonly used security provider.
Prerequisites:
OpenLegacy IDE (full installation including all the maven dependencies and JDK11)
JWT token
JWK-URI
OpenLegacy API and SDK
Step 1: Create an Okta instance
Follow the steps from this guide: Create OIDC app integrations.
Step 2: Create a Default Authorization Server Scope
Follow the steps from this guide to create a default scope: https://developer.okta.com/docs/guides/customize-authz-server/create-scopes/
Inside the Okta dashboard, go to the Applications → Applications → Name of App → Check
Client Credentials
box.
Step 3: Edit the API’s Pom.xml / build.gradle.kts
For IDE Project
Go to the API’s pom.xml.
Remove all the security-related dependencies (if any), including the test dependencies.
Add the following dependencies:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-client</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-resource-server</artifactId> </dependency>
For Low Code Project
Go to
build.gradle.kts
Add the following dependency:
implementation("org.springframework.boot:spring-boot-starter-security")
implementation("org.springframework.boot:spring-boot-starter-oauth2-client")
implementation("org.springframework.boot:spring-boot-starter-oauth2-resource-server")
Step 4: Security Configuration Class
For IDE Project
Copy the following class into
com.{your_api}.openlegacy.config
package.import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer; @Configuration public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests(authorizeRequests -> authorizeRequests.mvcMatchers("/swagger**/**") .permitAll() .anyRequest() .authenticated()) .oauth2Login(oauthLogin -> oauthLogin.permitAll()).oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt); } }
In this class, you can manage the endpoint's access as you wish.
In this example "/swagger**/**
is allowed and no authentication is required, but all the other endpoints require authentication.
For Low Code Project
Create config package and add new class (i.e.,
SecurityConfig
).Copy the following code snippet:
package com.openlegacy.config;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;
@EnableWebFluxSecurity
public class SecurityConfig {
@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
// @formatter:off
http.csrf().disable()
.authorizeExchange(
authorizeRequests -> authorizeRequests.
pathMatchers("/openapi/**").
permitAll().
anyExchange().
authenticated()).oauth2Login().and().oauth2ResourceServer().jwt();
return http.build();
// @formatter:on
}
}
Step 5: Application.yml.
Go to the Application.yml in the
man/src/resources
folderAdd the following configuration
spring: security: oauth2: resourceserver: jwt: jwk-set-uri: https://{okta_authorization_server_url}/oauth2/default/v1/keys client: registration: okta: client-id: {client_id} client-secret: {client_secret} provider: okta: issuer-uri: https://{okta_authorization_server_url}
Now you are ready to test your API.
Step 6: Get JWT Token
Open Postman and add a new POST request to
https://{okta_authorization_server_url}/oauth2/default/v1/token
Add header
Content-type
:application/x-www-form-urlencoded
For the body of the request select
x-www-form-urlencoded
-grant_type
:client_credentials
For Authorization select
Basic Auth
and, and for theusername
:client_id
,password
:client_secret
.Send the request.
Step 7: Execute the API
Copy the token from the previous step.
For Authorization, select
Bearer Token
and paste the token.Execute the API.
Step 8: Add Token to Swagger UI Request(Optional Step)
For IDE Project
Add the following security definition sample to
{projectName}OpenApiConfiguration.java
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI().components(new Components().addSecuritySchemes("bearer-key",
new SecurityScheme().type(SecurityScheme.Type.HTTP).scheme("bearer").bearerFormat("JWT")));
}
2. Add the @SecurityRequirement
tags to your protected APIs, for example:
@Operation(security = { @SecurityRequirement(name = "bearer-key") })
3. Click the Authorize
button in the Swagger UI.
4. Copy the token from step 6 and click Authorize
.
5. Execute the API.
For Low Code Project
Run Low Code project:
gradle bootRun
Navigate to
http://localhost:8080/openapi/openapi/openapi.yaml
Create
openapi.yaml
file insrc/main/resources
and copy the content from step 2.Add Bearer Authentication properties to
openapi.yaml
on the root level.# 1) Define the security scheme type (HTTP bearer) components: securitySchemes: bearerAuth: # arbitrary name for the security scheme type: http scheme: bearer bearerFormat: JWT # optional, arbitrary value for documentation purposes # 2) Apply the security globally to all operations security: - bearerAuth: [] # use the same name as above
Add the following properties to
application.yml
ol: spring: webflux: openapi: path: openapi.yaml
Re-run the Low Code project.
Click
Authorize
button in swagger UI.Paste the token and click
Authorize
button.Execute the API.
Example Project
Additional Info
Note, you can add the following configuration to get more information in the logs. logging.level.org.springframework.security: trace