Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • System Design Tutorial
  • What is System Design
  • System Design Life Cycle
  • High Level Design HLD
  • Low Level Design LLD
  • Design Patterns
  • UML Diagrams
  • System Design Interview Guide
  • Scalability
  • Databases
Open In App
Next Article:
Spring Security – Customizing Authentication and Authorization
Next article icon

API Gateway Authentication and Authorization in Spring Boot

Last Updated : 12 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In modern web applications, securing the communication between the clients and backend services is crucial. The API Gateway can serve as a reverse proxy and manage the client requests, and routing them to the appropriate backend services. It enhances the security, we can implement the authentication and authorization mechanisms using the JSON Web Tokens (JWT). JWT offers a compact and self-contained way to securely transmit information between the parties in a JSON object.

This article will guide you through setting up the API Gateway with Spring Boot that handles the authentication and authorization using JWT. We will create the endpoint for the user registration and login. Generate the JWT tokens upon successful login and validate these tokens for secure communication with the backend microservices.

Prerequisites:

  • Java Development Kit is installed on your local system.
  • Maven/Gradle tool for dependency management of Spring project.
  • Basic understanding of Spring Boot and Spring Cloud.
  • MySQL Database is installed and running on your local system

API Gateway and JWT

  • API Gateway: Acts as a single entry point for client requests, handling user authentication, generating JWT tokens, and routing requests to microservices. It centralizes security management, simplifying security and scalability.
  • JWT (JSON Web Tokens): Provides a secure way to transmit information between parties as a JSON object, compactly and self-contained.

Steps to Implement API Gateway Authentication and Authorization

  1. Setup the API Gateway Project: We will configure the Spring Boot for API Gateway, implement the security configurations and create the controllers for user registration and login of the application..
  2. JWT Token Generation and Validation: Implement the JWT utility classes to generate and validate tokens, ensuring secure communication.
  3. Setup Example Microservice: Create a simple backend microservice to demonstrate how requests are routed through the API Gateway.
  4. Testing the endpoints: We can use postman to test the registration, login and secure access to the microservice via API Gateway of the application.

Implementation of API Gateway Authentication and Authorization in Spring Boot

Below are the steps to authenticate and authorize the API Gateway in Spring Boot.

Step 1: Create a Spring Project

We will create the spring boot project using spring Initializr and on creating the project, add the below dependencies.

Dependencies:

  • Spring Web
  • Spring Gateway routing
  • Lombok
  • Spring DevTools
  • MySQL Driver

After the project creation done, the project folder structure will be like the below image:

Folder Structure

Note: Make sure, the API Gateway runs on port 8080 and the example microservice runs on port 8081.

Step 2: Application Properties

Open the application.properties file and rename it into the application.yml and add the configuration of MySQL database and gateway of the application.

server:
port: 8080

spring:
application:
name: api-gateway

datasource:
url: jdbc:mysql://localhost:3306/jwt
username: root
password:
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true

cloud:
gateway:
routes:
- id: example-service
uri: http://localhost:8081
predicates:
- Path=/example/**
default-filters:
- DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin

jwt:
secret: mySecretKey


Step 3: Create the User model

Go to src > main > java > org.example.gatewayuth > model > User and put the below code.

Java
package org.example.gatewayauth.model;   import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor;  @Entity @Data @AllArgsConstructor @NoArgsConstructor public class User {      @Id     @GeneratedValue(strategy = GenerationType.IDENTITY)     private Long id;     private String username;     private String password;     private String role;      // getters and setters } 

This User class defines a JPA entity for user details, including id, username, password, and role fields, with Lombok annotations (@Data, @AllArgsConstructor, @NoArgsConstructor) for automatic generation of getters, setters, constructors, and toString methods.

Step 4: Create the AuthenticationRequest Class

Go to src > main > java > org.example.gatewayuth > model > AuthenticationRequest and put the below code.

Java
package org.example.gatewayauth.model;   import lombok.Data;  @Data public class AuthenticationRequest {      private String username;     private String password;      // getters and setters } 

This AuthenticationRequest class represents a simple model for capturing username and password during authentication, leveraging Lombok's @Data annotation for automatic generation of getters, setters, constructors, and toString method.

Step 5: Create the AuthenticationResponse Class

Go to src > main > java > org.example.gatewayuth > model > AuthenticationResponse and put the below code.

Java
package org.example.gatewayauth.model;  public class AuthenticationResponse {      private final String jwt;      public AuthenticationResponse(String jwt) {         this.jwt = jwt;     }      public String getJwt() {         return jwt;     } } 

The AuthenticationResponse class encapsulates a JWT (JSON Web Token) string to be returned to clients after a successful authentication process. It provides a constructor to initialize the JWT and a getter method to retrieve it. This class is typically used to serialize the JWT into JSON format and send it back to the client as part of the authentication response.

Step 6: Create the UserRepository class

Go to src > main > java > org.example.gatewayuth > repository > UserRepository and put the below code.

Java
package org.example.gatewayauth.repository;   import org.example.gatewayauth.model.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository;  @Repository public interface UserRepository extends JpaRepository<User, Long> {     User findByUsername(String username); } 

The UserRepository interface extends JpaRepository<User, Long>, enabling CRUD operations for User entities. It includes a method findByUsername(String username) for retrieving users by their username from the database, leveraging Spring Data JPA's query generation capabilities. The @Repository annotation marks it as a Spring-managed repository component.

Step 7: Create the SecurityConfig Class

Go to src > main > java > org.example.gatewayuth > config > SecurityConfig and put the below code.

Java
package org.example.gatewayauth.config;   import org.example.gatewayauth.service.CustomUserDetailsService; import org.example.gatewayauth.util.JwtUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;  @Configuration @EnableWebSecurity public class SecurityConfig {      @Autowired     private JwtUtil jwtUtil;      @Autowired     private CustomUserDetailsService userDetailsService;      @Bean     public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {         http.csrf().disable()                 .authorizeRequests()                 .requestMatchers("/auth/**","auth/login").permitAll()                 .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()                 .anyRequest().authenticated()                 .and()                 .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);          http.addFilterBefore(new JwtAuthenticationFilter(jwtUtil), UsernamePasswordAuthenticationFilter.class);          return http.build();     }      @Bean     public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {         return authenticationConfiguration.getAuthenticationManager();     }      @Bean     public PasswordEncoder passwordEncoder() {         return new BCryptPasswordEncoder();     } } 

The SecurityConfig class configures JWT-based authentication and authorization for the API Gateway using Spring Security. It disables CSRF protection, permits public access to authentication endpoints (/auth/** and /auth/login), and sets up a stateless session management policy.

Step 9: Create the JwtAuthenticationFilter Class

Go to src > main > java > org.example.gatewayuth > config > JwtAuthenticationFilter and put the below code.

Java
package org.example.gatewayauth.config;  import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.example.gatewayauth.util.JwtUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.web.filter.OncePerRequestFilter;  import java.io.IOException;    public class JwtAuthenticationFilter extends OncePerRequestFilter {      private final JwtUtil jwtUtil;      @Autowired     private UserDetailsService userDetailsService;      @Autowired     public JwtAuthenticationFilter(JwtUtil jwtUtil) {         this.jwtUtil = jwtUtil;     }      @Override     protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)             throws ServletException, IOException {         final String authorizationHeader = request.getHeader(HttpHeaders.AUTHORIZATION);          String username = null;         String jwt = null;          if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {             jwt = authorizationHeader.substring(7);             username = jwtUtil.extractUsername(jwt);         }          if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {             UserDetails userDetails = userDetailsService.loadUserByUsername(username);             if (jwtUtil.validateToken(jwt, userDetails)) {                 UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());                 authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));                 SecurityContextHolder.getContext().setAuthentication(authentication);             }         }         chain.doFilter(request, response);     } } 

The JwtAuthenticationFilter class intercepts incoming requests to validate JWT tokens for authentication in Spring Security. It extracts the JWT from the Authorization header, verifies its validity using JwtUtil, and sets the authenticated UserDetails in the security context.

Step 10: Create the JwtUtil Class

Go to src > main > java > org.example.gatewayuth > util > JwtUtil and put the below code.

Java
package org.example.gatewayauth.util;   import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Component;  import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.function.Function;  @Component public class JwtUtil {      @Value("${jwt.secret}")     private String secret;      public String extractUsername(String token) {         return extractClaim(token, Claims::getSubject);     }      public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {         final Claims claims = extractAllClaims(token);         return claimsResolver.apply(claims);     }      public Claims extractAllClaims(String token) {         return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();     }      public Boolean validateToken(String token, UserDetails userDetails) {         final String username = extractUsername(token);         return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));     }      private Boolean isTokenExpired(String token) {         return extractExpiration(token).before(new Date());     }      public Date extractExpiration(String token) {         return extractClaim(token, Claims::getExpiration);     }      public String generateToken(UserDetails userDetails) {         Map<String, Object> claims = new HashMap<>();         return createToken(claims, userDetails.getUsername());     }      private String createToken(Map<String, Object> claims, String subject) {         return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))                 .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10))                 .signWith(SignatureAlgorithm.HS256, secret).compact();     } } 

The JwtUtil class facilitates JWT token handling in Spring Security:

  • It extracts username and claims from tokens, validates token authenticity against user details, and generates new tokens with specified expiration.
  • Utilizes io.jsonwebtoken for parsing and signing tokens, ensuring secure authentication and authorization mechanisms in applications

Step 11: Create the JwtService Class

Go to src > main > java > org.example.gatewayuth > service > JwtService and put the below code.

Java
package org.example.gatewayauth.service;   import org.example.gatewayauth.model.AuthenticationRequest; import org.example.gatewayauth.util.JwtUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Service;  @Service public class JwtService {      @Autowired     private AuthenticationManager authenticationManager;      @Autowired     private CustomUserDetailsService userDetailsService;      @Autowired     private JwtUtil jwtUtil;      public String createJwtToken(AuthenticationRequest authenticationRequest) throws Exception {         authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(                 authenticationRequest.getUsername(), authenticationRequest.getPassword()));          final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername());         return jwtUtil.generateToken(userDetails);     } } 

The JwtService class handles JWT token creation by authenticating user credentials, loading user details, and generating the token using JwtUtil.

Step 12: Create the CustomUserDetailsService Class

Go to src > main > java > org.example.gatewayuth > service > CustomUserDetailsService and put the below code.

Java
package org.example.gatewayauth.service;   import org.example.gatewayauth.model.User; import org.example.gatewayauth.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service;  import java.util.ArrayList;  @Service public class CustomUserDetailsService implements UserDetailsService {      @Autowired     private UserRepository userRepository;      @Override     public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {         User user = userRepository.findByUsername(username);         if (user == null) {             throw new UsernameNotFoundException("User not found with username: " + username);         }         return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), new ArrayList<>());     } } 

The CustomUserDetailsService class implements UserDetailsService, loading user details from the UserRepository and throwing an exception if the user is not found.

Step 13: Create the UserService Class

Go to src > main > java > org.example.gatewayauth > service > UserService and put the below code.

Java
package org.example.gatewayauth.service;   import org.example.gatewayauth.model.User; import org.example.gatewayauth.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service;  @Service public class UserService {      @Autowired     private UserRepository userRepository;      @Autowired     private PasswordEncoder passwordEncoder;      public User save(User user) {         user.setPassword(passwordEncoder.encode(user.getPassword()));         return userRepository.save(user);     }      public User findByUsername(String username) {         return userRepository.findByUsername(username);     } } 

The UserService class provides user management functionalities, such as saving a user with an encoded password and finding a user by username, leveraging UserRepository and PasswordEncoder.

Step 14: Create the AuthController Class

Go to src > main > java > org.example.gatewayuth > controller > AuthController and put the below code.

Java
package org.example.gatewayauth.controller;    import org.example.gatewayauth.model.AuthenticationRequest; import org.example.gatewayauth.model.AuthenticationResponse; import org.example.gatewayauth.model.User; import org.example.gatewayauth.service.JwtService; import org.example.gatewayauth.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*;  @RestController @RequestMapping("/auth") public class AuthController {      @Autowired     private JwtService jwtService;      @Autowired     private UserService userService;      @PostMapping("/login")     public ResponseEntity<?> createAuthenticationToken(@RequestBody AuthenticationRequest authenticationRequest) throws Exception {         final String jwt = jwtService.createJwtToken(authenticationRequest);         return ResponseEntity.ok(new AuthenticationResponse(jwt));     }      @PostMapping("/signup")     public ResponseEntity<?> registerUser(@RequestBody User user) {         if (userService.findByUsername(user.getUsername()) != null) {             return ResponseEntity.badRequest().body("Username is already taken.");         }         userService.save(user);         return ResponseEntity.ok("User registered successfully.");     } } 

The AuthController handles user authentication and registration requests, using JwtService to generate JWT tokens for login and UserService to register new users and check if a username is already taken.

Step 14: Main Class

No changes are required in the main class.

Java
package org.example.gatewayauth;  import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;  @SpringBootApplication public class GatewayAuthApplication {      public static void main(String[] args) {         SpringApplication.run(GatewayAuthApplication.class, args);     }  } 


pom.xml:

XML
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">     <modelVersion>4.0.0</modelVersion>     <parent>         <groupId>org.springframework.boot</groupId>         <artifactId>spring-boot-starter-parent</artifactId>         <version>3.3.0</version>         <relativePath/> <!-- lookup parent from repository -->     </parent>     <groupId>org.example</groupId>     <artifactId>gateway-auth</artifactId>     <version>0.0.1-SNAPSHOT</version>     <name>gateway-auth</name>     <description>gateway-auth</description>     <properties>         <java.version>17</java.version>     </properties>     <dependencies>                <dependency>             <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-starter-data-jpa</artifactId>         </dependency>                <dependency>             <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-starter-web</artifactId>         </dependency>          <dependency>             <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-starter-security</artifactId>         </dependency>          <!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt -->         <dependency>             <groupId>io.jsonwebtoken</groupId>             <artifactId>jjwt</artifactId>             <version>0.12.5</version>         </dependency>          <dependency>             <groupId>io.jsonwebtoken</groupId>             <artifactId>jjwt-api</artifactId>             <version>0.11.2</version>         </dependency>                <dependency>             <groupId>io.jsonwebtoken</groupId>             <artifactId>jjwt-impl</artifactId>             <version>0.11.2</version>             <scope>runtime</scope>         </dependency>                <dependency>             <groupId>io.jsonwebtoken</groupId>             <artifactId>jjwt-jackson</artifactId>             <version>0.11.2</version>             <scope>runtime</scope>         </dependency>                <dependency>             <groupId>org.springframework.security</groupId>             <artifactId>spring-security-core</artifactId>         </dependency>  	<dependency> 	    <groupId>org.springframework.cloud</groupId> 	    <artifactId>spring-cloud-starter-gateway-mvc</artifactId> 	</dependency>      <dependency>         <groupId>org.springframework.boot</groupId>         <artifactId>spring-boot-devtools</artifactId>         <scope>runtime</scope>         <optional>true</optional>     </dependency>            <dependency>         <groupId>com.mysql</groupId>         <artifactId>mysql-connector-j</artifactId>         <scope>runtime</scope>     </dependency>      <dependency>         <groupId>org.projectlombok</groupId>         <artifactId>lombok</artifactId>         <optional>true</optional>     </dependency>      <dependency>         <groupId>org.springframework.boot</groupId>         <artifactId>spring-boot-starter-test</artifactId>         <scope>test</scope>     </dependency>          </dependencies>    <dependencyManagement>       <dependencies>           <dependency>               <groupId>org.springframework.cloud</groupId>               <artifactId>spring-cloud-dependencies</artifactId>                   <version>${spring-cloud.version}</version>               <type>pom</type>               <scope>import</scope>           </dependency>       </dependencies>   </dependencyManagement>      <build>         <plugins>             <plugin>                 <groupId>org.springframework.boot</groupId>                 <artifactId>spring-boot-maven-plugin</artifactId>                 <configuration>                     <excludes>                         <exclude>                             <groupId>org.projectlombok</groupId>                             <artifactId>lombok</artifactId>                         </exclude>                     </excludes>                 </configuration>             </plugin>         </plugins>     </build>  </project> 


Step 16: Run the Application

Once completed, run the application and it will start at port 8080.

Application Runs


Creation of one more Microservice (example-microservice)

Below are the implementation steps.

Step 1: Create the Spring Project

We will create the spring Boot project using spring Initializr and add the below dependencies into the project.

Dependencies:

  • Spring Web
  • Lombok
  • Spring DevTools

Once create the project then the file structure looks like the below image.

Project Folder Structure


Step 2: Application properties

server:
port: 8081

spring:
application:
name: example-microservice

Step 3: Create the GreetingController Class

Go to src > main > java > org.example.examplemicroservice > GreetingController and put the below code.

Java
package org.example.examplemicroservice;  import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;  @RestController @RequestMapping("/example") public class GreetingController {      @GetMapping("/greeting")     public String greeting() {         return "Hello from Example Microservice!";     } } 

The GreetingController in this Spring Boot application handles HTTP GET requests at /example/greeting, responding with the message "Hello from Example Microservice!"

Step 4: Main class

No changes are required in the main class.

Java
package org.example.examplemicroservice;  import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;  @SpringBootApplication public class ExampleMicroserviceApplication {      public static void main(String[] args) {         SpringApplication.run(ExampleMicroserviceApplication.class, args);     }  } 


pom.xml file of example-microservice:

XML
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">     <modelVersion>4.0.0</modelVersion>     <parent>         <groupId>org.springframework.boot</groupId>         <artifactId>spring-boot-starter-parent</artifactId>         <version>3.3.0</version>         <relativePath/> <!-- lookup parent from repository -->     </parent>     <groupId>org.example</groupId>     <artifactId>example-microservice</artifactId>     <version>0.0.1-SNAPSHOT</version>     <name>example-microservice</name>     <description>example-microservice</description>     <properties>         <java.version>17</java.version>     </properties>     <dependencies>                <dependency>             <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-starter-web</artifactId>         </dependency>          <dependency>             <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-devtools</artifactId>             <scope>runtime</scope>             <optional>true</optional>         </dependency>                <dependency>             <groupId>org.projectlombok</groupId>             <artifactId>lombok</artifactId>             <optional>true</optional>         </dependency>                <dependency>             <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-starter-test</artifactId>             <scope>test</scope>         </dependency>            </dependencies>      <build>         <plugins>             <plugin>                 <groupId>org.springframework.boot</groupId>                 <artifactId>spring-boot-maven-plugin</artifactId>                 <configuration>                     <excludes>                         <exclude>                             <groupId>org.projectlombok</groupId>                             <artifactId>lombok</artifactId>                         </exclude>                     </excludes>                 </configuration>             </plugin>         </plugins>     </build>  </project> 


Step 5: Run the Application

Once completed, run the application and it will start at port 8081.

example-microservice Runs


Step 6: Testing the Endpoints

Signup Endpoint:

POST http://localhost:8080/auth/signup

Output:

Signup Endpoint


login Endpoint:

POST http://localhost:8080/auth/login

Output:

login Endpoint


example-microservice's greeting Endpoint:

GET http://localhost:8080/example/greeting

Output:

greeting Endpoint

This example demonstrates the implementation of the API Gateway Authentication and Authorization in Spring Boot.


Next Article
Spring Security – Customizing Authentication and Authorization

S

seepanarajvskq
Improve
Article Tags :
  • Advance Java
  • Java-Spring-Boot
  • Java-Spring-Security
  • Java Microservices

Similar Reads

  • Spring Boot - OAuth2 Authentication and Authorization
    OAuth2 is a widely-used protocol for authorization that enables applications to securely access resources on behalf of users. When combined with Spring Boot, OAuth2 facilitates authentication and authorization for both REST APIs and web applications. This article will walk you through setting up OAu
    7 min read
  • Authentication and Authorization with OAuth
    OAuth (Open Authorization) is the open standard for token-based authentication and authorization on the Internet. It can allow third-party services to exchange information without exposing the user credentials. In this article, we will guide you on how to implement the OAuth in the MERN stack applic
    7 min read
  • Spring Security – Customizing Authentication and Authorization
    Spring Security is the powerful and customizable framework that provides the authentication, authorization, and other security features for the Java applications, especially the Spring-based ones. When building secure applications, controlling access to resources is important. Customizing authorizat
    7 min read
  • Authentication and Authorization in Microservices
    In microservices, ensuring data security is paramount. Authentication and authorization are two crucial components of this security framework. This article provides a straightforward overview of how authentication verifies user identity and how authorization controls access to resources within micro
    11 min read
  • Authentication and Authorization with JWT in a GraphQL
    Authentication and authorization are important aspects of building secure web applications by including those powered by GraphQL. JSON Web Tokens (JWT) provide a popular mechanism for implementing authentication and authorization in GraphQL applications. In this article, we'll explore the concepts o
    6 min read
  • Implementing Database Authentication and Authorization with Spring Security 6
    Spring Security 6 has made setting up security in Spring applications easier and more straightforward by moving away from the older WebSecurityConfigurerAdapter method. This new approach helps you configure security in a clearer and more flexible way. In this article, we will learn how to set up use
    9 min read
  • Difference between Authentication and Authorization in LLD - System Design
    Two fundamental ideas in system design, particularly in low-level design (LLD), are authentication and authorization. While authorization establishes what resources or actions a user is permitted to access, authentication confirms a person's identity. Both are essential for building secure systems b
    4 min read
  • OAuth2 Authentication with Spring and Github
    OAuth2 is a secure way to allow users to log in to your application using third-party providers like GitHub. Instead of creating a custom login system, we can use GitHub’s authentication to verify users and grant access. Working of OAuth2Imagine a user wants to log in to your app using GitHub. When
    2 min read
  • How to Configure AuditListener in Spring Boot Application
    Spring Boot Data provides support to transparently keep track of who created an entity or changed an entity and when these things happened. All records are maintained clearly. For example, if one user comes into the site and logs in to the site. Then those times are maintained in the database and al
    4 min read
  • Spring Security - In-Memory Authentication
    Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications. Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences