Comprehensive Guide to Building an OAuth2 Authentication Server with Spring Boot, MySQL, Nacos, and Gateway Integration

This tutorial walks through designing an OAuth2 authentication architecture, configuring Spring Boot services, setting up MySQL schemas, integrating Nacos discovery, implementing security with JWT tokens, and connecting microservices through a Spring Cloud Gateway, while demonstrating all four OAuth2 grant types with code examples.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Comprehensive Guide to Building an OAuth2 Authentication Server with Spring Boot, MySQL, Nacos, and Gateway Integration

This article presents a complete step‑by‑step guide for constructing a unified authentication system based on OAuth2 using Spring Boot, MySQL, Nacos, and Spring Cloud Gateway.

1. Architecture Overview – An authentication diagram shows the registration center, authorization server, and gateway, followed by service and version listings.

2. OAuth2 Core Interfaces – Describes the main endpoints /oauth/token, /oauth/check_token, and /oauth/authorize, including their locations in the Spring Security classes.

3. Database Design – Provides DDL for oauth_client_details, oauth_access_token, oauth_refresh_token, and sys_user tables, with sample INSERT statements and password encryption using BCryptPasswordEncoder.

/*
 Navicat Premium Data Transfer
 Source Server         : win-local
 Source Server Version : 50737
*/
SET NAMES utf8mb4;
DROP TABLE IF EXISTS `oauth_client_details`;
CREATE TABLE `oauth_client_details` (
  `client_id` varchar(128) NOT NULL COMMENT '客户端ID',
  `client_secret` varchar(256) NOT NULL COMMENT '客户端密匙',
  `grant_type` varchar(256) NOT NULL COMMENT '支持的grant_type',
  `access_token_validity` int DEFAULT NULL COMMENT 'access token 有效期(秒)',
  `refresh_token_validity` int DEFAULT NULL COMMENT 'refresh token 有效期(秒)'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `oauth_client_details` VALUES ('client-app','$2a$10$...','password,refresh_token,client_credentials,authorization_code,implicit',3600,86400);

4. Maven Configuration (pom.xml) – Lists essential dependencies such as spring-cloud-starter-oauth2, MySQL connector, MyBatis‑Plus, Druid, and Lombok.

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
  <groupId>org.mybatis.spring.boot</groupId>
  <artifactId>mybatis-spring-boot-starter</artifactId>
  <version>2.1.4</version>
</dependency>

5. Application Configuration (application.yml) – Shows MySQL, Nacos, Redis, and MyBatis settings, emphasizing spring.application.name for service registration.

server:
  port: 9010
spring:
  application:
    name: oauth2-server-service
  datasource:
    url: jdbc:mysql://localhost:3306/oauth2?useSSL=false
    username: root
    password: root

6. Authorization Server Setup – Implements AuthorizationServerConfigurerAdapter with a JDBC client details service, JdbcTokenStore (or RedisTokenStore), and form‑authentication enabling.

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired private DataSource dataSource;
    @Bean public ClientDetailsService customClientDetailsService() {
        return new JdbcClientDetailsService(dataSource);
    }
    public JdbcTokenStore jdbcTokenStore() { return new JdbcTokenStore(dataSource); }
    @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(customClientDetailsService());
    }
    @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.tokenStore(jdbcTokenStore());
    }
}

7. Resource Server Configuration – Secures /api/** endpoints using ResourceServerConfigurerAdapter.

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Override public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated()
            .and().requestMatchers().antMatchers("/api/**");
    }
}

8. Spring Security (WebSecurityConfigurerAdapter) – Defines password encoder, authentication manager, and permits login URLs.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); }
    @Override protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().httpBasic()
            .and().authorizeRequests()
            .antMatchers("/login/**","/logout/**").permitAll()
            .anyRequest().authenticated()
            .and().formLogin().permitAll();
    }
}

9. MyBatis Integration for User Details – Custom UserDetailsService loads users from sys_user and maps roles to SimpleGrantedAuthority.

@Service
public class CustomUserDetailServiceImpl implements UserDetailsService {
    @Autowired private UserService userService;
    @Override public UserDetails loadUserByUsername(String username) {
        SecurityUser user = userService.selectUserByUserName(username);
        if (!user.isEnabled()) throw new DisabledException("Account disabled");
        return new User(username, user.getPassword(), new ArrayList<>());
    }
}

10. Gateway Integration – Configures Spring Cloud Gateway routes to forward /auth-server/** and /user/** to the respective services via Nacos discovery, with StripPrefix=1 and retry filters.

spring:
  cloud:
    gateway:
      routes:
        - id: auth-service-route
          uri: lb://oauth2-server-service
          predicates:
            - Path=/auth-server/**
          filters:
            - StripPrefix=1

11. Testing the Gateway – Demonstrates calling localhost:9000/auth-server/api/hello and handling 401 responses, adding spring-cloud-loadbalancer to resolve 503 errors.

12. Four OAuth2 Grant Types – Shows how to use authorization code, implicit, password, and client‑credentials flows, including required request parameters and sample Postman calls.

# Authorization Code
GET http://localhost:9010/oauth/authorize?client_id=client-app&response_type=code
# Implicit
GET http://localhost:9010/oauth/authorize?grant_type=implicit&client_id=client-app&response_type=token
# Password
POST http://localhost:9010/oauth/token
 grant_type=password&username=bing&password=123456&client_id=client-app&client_secret=asdfholu12josadf#
# Client Credentials
POST http://localhost:9010/oauth/token
 grant_type=client_credentials&client_id=client-app&client_secret=asdfholu12josadf#

By following these steps, developers can set up a secure, scalable OAuth2 authentication server, expose protected resources, and route all traffic through a centralized gateway, supporting all major grant types for diverse client scenarios.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

MicroservicesNacosSpring BootSecuritygatewayOAuth2
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.