Enable JWT Token Validation - OpenLegacy API

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:

  1. OpenLegacy IDE (full installation including all the maven dependencies and JDK11)

  2. JWT token

  3. JWK-URI

  4. OpenLegacy API and SDK

 

Step 1: Create an Okta instance 

  1. Follow the steps from this guide: Create OIDC app integrations.

Step 2: Create a Default Authorization Server Scope

  1. Follow the steps from this guide to create a default scope: https://developer.okta.com/docs/guides/customize-authz-server/create-scopes/

  2. 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

  1. Go to the API’s pom.xml.

  2. Remove all the security-related dependencies (if any), including the test dependencies.

  3. 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

  1. Go to build.gradle.kts

  2. 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

  1. 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

  1. Create config package and add new class (i.e., SecurityConfig).

  2. 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.

  1. Go to the Application.yml in the man/src/resources folder

  2. Add 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

  1. Open Postman and add a new POST request to https://{okta_authorization_server_url}/oauth2/default/v1/token

  2. Add header Content-type: application/x-www-form-urlencoded

  3. For the body of the request select x-www-form-urlencoded - grant_type:client_credentials

  4. For Authorization select Basic Auth and, and for the username: client_id, password: client_secret.

  5. Send the request.

Step 7: Execute the API

  1. Copy the token from the previous step.

  2. For Authorization, select Bearer Token and paste the token.

  3. Execute the API.

Step 8: Add Token to Swagger UI Request(Optional Step)

For IDE Project

  1. 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

  1. Run Low Code project: gradle bootRun

  2. Navigate to http://localhost:8080/openapi/openapi/openapi.yaml

  3. Create openapi.yaml file in src/main/resources and copy the content from step 2.

  4. 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

     

  5. Add the following properties to application.yml

    ol: spring: webflux: openapi: path: openapi.yaml

     

  6. Re-run the Low Code project.

  7. Click Authorize button in swagger UI.

  8. Paste the token and click Authorize button.

  9. 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